The while loop is something between a for loop and a do while loop and can also be a means to translate an if statement into a shorter form. It's main feature in common with the for loop is the condition being checked at the beginning of the loop, meaning that it does not necessarily run at all. On the other hand the do while loop runs at least once, if the condition is realistic in current settings.
The while loop, like the for loop and the do while loop, allows for repetition of a statement as long as the end condition is met. Semantically, the while loop can be written as follows:
while(end condition)
{statement list}
First of all, the condition is written at the very beginning of the loop and so it is checked before anything else is executed, and that way if the condition is not fulfilled, nothing is done.
It is worth noting that the curly braces are not required when we want to execute only one statement, whereas in the do while loop, braces are required even for only one statement.
Another thing to remember is that there is no semicolon after the curly braces, whereas in the case of the do while loop, the semicolon is there.
Simple examples of using the while loop:
#include <iostream>
using namespace std;
int main()
{
int how_many = 6;
while(how_many)
cout << 'I am inside the while loop' << endl;
cout << endl << 'Press Enter to finish.' << endl;
getchar(); #Returns the code of the read character in case of success. The read character is returned in form of an int.
return 0;
}
Run the above program to see that none of the inside statements get executed. Can you guess why?
And here is another example of a problematic program:
#include <iostream>
using namespace std;
int main()
{
int how_many = 4;