Read Time:39 Second
The while loop is used when we want the loop to execute and continue executing while the specified condition is true. As the condition is checked at the beginning of the loop, it is also called entry controlled loop.
Syntax:
init-statement while (condition) { statement iteration-expression; }
Example:
See the program below.
#include <iostream> using namespace std; int main() { int i = 1; //while loop while (i <= 5) { cout << "The number is " << i << endl; i = i + 1; } return 0; };
Output:
The number is 1 The number is 2 The number is 3 The number is 4 The number is 5
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
[…] while loop – loops through a block of code while a specified condition is true. […]