-5

So I am trying to write a basic program that asks the user to input any number other than 5, and after 10 iterations of the user not entering the number 5, I want the program to print to screen. Here is my code so far:

#include <iostream>
#include <string>
using namespace std;

int main(){

    int num;

    cout << "Please enter a number other than 5." << endl;
    cin >> num;

    while (num != 5){
        cout << "Please enter a number other than 5." << endl;
        cin >> num;
    }

    return 0;
}

I just don't know how to tell the computer to stop the loop at 10 iterations and output to the screen.

Louis Smith
  • 27
  • 1
  • 8
  • 3
    Keep track with a counter.. – Andrew Li Aug 03 '16 at 04:02
  • What happens if the user enters 5 during the `while` loop? – Vaibhav Bajaj Aug 03 '16 at 04:23
  • Hey Louis! **Welcome to Stackoverflow!!!** ... From your question, I will recommend you to please check [**this**](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) out and make at least two selections, read them, then you can come back here and ask your question.. We will be more than happy to help you :-) – WhiZTiM Aug 03 '16 at 04:27

2 Answers2

1

this is a suitable time to utilize the

do while

loop

the way it works is it will execute the statement within the block without evaluating any conditions and then evaluate the condition to determine if the loop should run again

this is what your program could look like

#include <iostream>
using namespace std;

int main(void)
{
int counter = 0, num;
do
{
if (counter > 10) // or >=10 if you want to display if it is 10
{
cout << "exiting the loop!" << endl;
break; // the break statement will just break out of the loop
}
cout << "please enter a number not equal to 5" << endl;
cin >> num;
counter++; // or ++counter doesn't matter in this context

}
while ( num != 5);
return 0;
} 
hec
  • 98
  • 9
-2
#include <iostream>
#include <string>
using namespace std;

int main(){

    int num;
    int counter=1;

   cin >> num;
   cout <<num;
   if(num==5) 
    cout << "Please enter a number other than 5." << endl;



    while (num != 5&&counter<=10){
        cin >> num;
        cout <<num;
        if(num==5) 
        cout << "Please enter a number other than 5." << endl;
        counter=counter+1;
    }

    return 0;
}
rUCHit31
  • 334
  • 1
  • 3
  • 15