Explain Loops – While loop, Do-while loop, for loop.
- Loops are used to carry out certain instruction(s) in continuation for a fixed no of times.
-
Syntax of while loop ://initialization statement(s)
while (condition)
{
//statement1;
//statement2;
….
….
}
-
Example :x = 0; // initialization stmt
while (x < 10)
{
cout << x<<”\n”;
x ++;
}
- This prints numbers 0 to 9 on the screen.
Do- while loop :- This is similar to while loop; the only difference is unlike while loop, in do-while loop condition is checked after the loop statements are executed. This means the statements in the do while loop are executed at least once; even if the condition fails for the first time itself.
-
Syntax of Do-while loop://initialization stmt(s)
do
{
Statement1;
Statement2;
}
while (condition)
Example :x = 0; // initialization stmt
do
{
cout << x<<”\n”;
x ++;
}
while (x < 10);
- This prints numbers 0 through 9 on the screen.
For loop :- It does exactly the same thing as while loop; only difference is the initialization, the condition statement is written on the same line.
- This is used when we want to execute certain statements for a fixed number of times.
- This is achieved by initializing a loop counter to a value and increasing or decreasing the value for certain no of times until a condition is satisfied.
- The loop statements are executed once for every iteration of the for loop.
-
Syntax of For loop:for (initialize loop counter; condition checking; increasing/decreasing loop counter)
{
//statement1;
//statement2;
}
-
Example :for (x = 0; x < 10; x++)
{
cout << x <<”\n”;
}
- This code snippet will print numbers 0 to 9.