For Loop C++:
Loops are basically used when we need to execute a block of
statement multiple times until a condition is satisfied, for
example we need to print 1 to 100 so we will set a variable as 1
and loop till the variable is 100 increment by 1 every
iteration.
In c++ we have loops such as for loop and while loop
For Loop:
Syntax of for loop:
for(initialization; condition;increment/decrement){
code to execute
}
steps in which a for loop is executed is
first step is the initialization where the variable is initialized,
and this happens only once in a for loop, in the second step the
condition in the loop is executed for each iteration, if the
condition is satisfied and if the condition is false then the
statement in the loop does not execute and loop terminates and the
control get tranfered to the next statement after for loop.
step 3 is after every execution of the loop body increment or
decrement happens, after this the condition in the second step is
again re-evaluated and the loop continues if the condition is
satisfied.
Example of a for loop
for(int i=0;i<100;i++){
cout<<i<<endl;
}
this loop prints 0 to 99 on the screen.
While loop:
Syntax of a while loop:
while(condition){
code block of while loop
}
In a while loop the condition in the while loop is executed first and if the condition is satisfied or gets true then the loop body executes and loop body executes until the condition is true, when condition is false then control is tranfered to the next statement of the while loop. It is important to use increment or decrement statement inside while loop so that the loop variable gets changed in every iteration and after some point the condition gets false and if we do not provide increment or decrement then the loop becomes an infinite loop and never terminates.
Example of a while loop
int i=0
while(i<100){
cout<<i<<endl;
i++;
}
this loop will also print 0 to 99 incrementing by 1 on every
line.
if you like the answer please provide a thumbs up.
Peer Interaction: Loops You've worked hard to understand the different types of loops in C++. For...