C++: Combining while loop and if statement

The while loop will check for a condition and will continue to run the loop if the condition is not met.

For certain condition, you might want to perform a specific task.  You can use if statement to check for this condition.

Consider the following example.

#include <iostream>
using namespace std;

void main()
{
	int i = 0;

	cout << "Please enter a value between 0 and 10" << endl;

	cin >> i;

	while ((i != 1) && (i != 10))
	{	

		if (i > 10)
		{
			cout << "You have entered a right value that is larger than 10.";
		}

		cout << "Please enter a value between 0 and 10" << endl;
		cin >> i;

	}

	cout << "You have entered the right value";
}

If 1 or 10 is entered, it will exit the while loop.  If a value larger than 10 is entered, a message will be printed out and it will still continue to run the while loop.

In line 12, we have introduced 2 new operators.  The != which is not equal and the && which is the and operator.

You can refer to C++ operator in this wiki page.

whileif

Series Navigation<< C++: The while loop
C++: Logical operators >>