Loops
While Loop
For Loop
Do While Loop
Examples
Nested Loops
When you are repeating certain action again & again!
When we want to repeat a set of instructions again & again
In programming, we often encounter situations, when a block of code needs to be executed several number of times.
A loop statement allows us to execute a statement or group of statements multiple times.
Example - Say count 50 steps on treadmill.
// initialisation
while(condition){
// code block
// update
}
The while loop loops through a block of code as long as a specified condition is true.
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
for(init; condition ; update){
// code block
}
For loop is very similar to while loop, it combines the 3 steps that have seen in a single line. Both for loop and while loop can be used interchangeably and have same performance.
for(int step=1; step<=5 ; step=step+1){
// code block
cout << step <<endl;
}
The do/while loop is a exit controlled loop.
This loop will execute the code block at-least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true
do {
// code block to be executed
}
while (condition);
The do/while loop is a exit controlled loop.
This loop will execute the code block at-least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5)
The do/while loop is a exit controlled loop.
This loop will execute the code block at-least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5)
Break statement is used to explicitly terminate the loop based upon a certain condition.
As soon as the break statement is encountered from within a loop, the loop stops and control returns from the loop immediately to the first statement after the loop.
while(....){
if(condition){
break;
}
}
It is also a control statement, it takes control to execute the next iteration of the loop.
while(....){
if(condition){
continue;
}
}