Loops:
A loop repeatedly executes a set of statements until a particular condition is satisfied.
A while loop statement repeatedly executes a target statement as long as a given condition remains true.
Syntax:
while(condition)
{
statement(s);
}
The loop iterates while the condition is true.
The loop's body is the block of statements within curly braces.
For example:
int num=1;
while(num<6)
{
cout<<"Number: "<<num<<endl;
num=num+1;
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
The example above declares a variable equal to 1 (int num=1)
.
The while loop checks the condition (num<6)
, and executes the statements in its body, which increment the value of num
by one each time the loop runs.
The increment value can be changed. If changed, the number of times the loop is run will change, as well.
For example:
int num=1;
while(num<6)
{
cout<<"Number: "<<num<<endl;
num=num+3;
}
Output:
Number: 1
Number: 4