The while loop gets its name from the way it works: while a condition is true, do some task. The loop has two parts: (1) a condition that is tested for a true or false value, and (2) a statement or set of statements that is repeated as long as the condition is true.
while loop statement
The diamond symbol represents the condition that is tested. Notice what happens if the condition is true: one or more statements are executed and the program's execution flows back to the point just above the diamond symbol. The condition is tested again, and if its is true, the process repeats. If the condition is false, the program exits the loop.
The general form of the while statement is:
while (condition) {
statement sequence:
}
where:
condition is a relational expression that determines when the loop will exit
statement sequence may either be a single statement or a block of statements that make up the loop body
Example 1:
/* Write a program that will print the numbers 1 to 10 */
#include <iostream>
using namespace std;
int x;
int main () {
x=1;
while (x<=10) {
cout<< x << "\t";
x++;
}
return 0;
}
SAMPLE OUTPUT:
1 2 3 4 5 6 7 8 9 10
Note: For while loops that will execute multiple statements, braces are needed
Example 2:
A program that will print the sum of 1 to 10
#include <iostream>
using namespace std;
int main() {
int num = 1, sum = 0;
while (num <= 10) {
sum = sum + num;
num = num + 1;
count<<"\nThe Sum of 1 to 10 is " << sum;
}
return 0;
}
SAMPLE OUTPUT
The Sum of 1 to 10 is 55