Explain loop control statements

Estudies4you
Q34. Explain loop control statements.
Answer:

Loop control statements are the statements which are executed repeatedly until a condition i is satisfied. The following are the loop control statements.
  1. for statement
  2. while statement
  3. do-while statement.
1. ‘for’ Statement
“for’ statement executes for specific number of times. It contains three expressions each separated by semicolon. Initially, the loop variable is initialized to some value. The second expression is a condition. The loop body will be executed when this condition evaluates to true. After each iteration it increases by a specified value as mentioned in third expression.
Syntax
for (initializing expression; testing expression; updating expression)
{
statements;
}
Here, the initialization expression represents the initial value. The testing expression is a condition that is tested at each pass. The program is executed till this condition remains true. Updating expression is an unary expression that is either incremented or decremented to change the initial value. The conditional expression is evaluated and tested at the beginning while unary expression is evaluated at the end of each pass.
Figure: Flowchart of for Statement

Example
#include<iostream.h>
#include<conio.h>
main()
{
int i;
clrscr( );
for (i= 1; i<= 10; i++)
cout <<“Hello”<<endl;
getch( );
return 0;
}

Output:

2. while Statement:
The ‘while’ statement will be executed repeatedly as long as the expression remains true.
Syntax
while (expression)
{
body of the loop;
}

When the ‘while’ is reached, the computer evaluates expression. If it is found to be false, body of loop will not be executed and the loop terminates. Otherwise, the body of loop will be executed repeatedly, till the expression becomes false.
Figure (1): Flowchart of while Statement

Example
#include <iostream.h>
#include<conio.h>
main()
{
inti=1;
clrscr();
while(i <= 10)
{
cout<<“Hello”<<endl;
i++
}
getch();
return 0;
}

Output:

3. do-while Statement
It is similar to that of ‘while’ loop except that it is executed at least once. The test of expression is done after each time body of loop is executed. Initially, the statements of the body are executed and then the condition is checked. If it evaluates to true then the body of loop executes again. This will be repeated until the condition evaluates to false.
Syntax
do
{
body of loop;
} while (expression);

Figure (2): Flowchart of do-while Statement

Example
#include<iostream.h>
#include<conio.h>
main( )
{
int i=1;
clrscr();
do
{
cout<<“Hello”<<endl;
i++;
}
while(i <= 10);
getch();
return 0;
}


Output:


To Top