0
1.1kviews
Explain Control loops (looping) in C
1 Answer
0
10views

The C language provides for three loop constructs for performing loop operations. They are

• The while statement

• The do statement

• The for statement

• The while statement

The basic format of the while statement is

while(test condition) 
{
 body of the loop ;
}

The while is an entry–controlled loop statement. The test-condition is evaluated and if the condition is true, then the body of the loop is executed. After execution of the body, the test-condition is once again evaluated and if it is true, the body is executed once again.

This process of repeated execution of the body continues until the test-condition finally becomes false and the control is transferred out of the loop.

Eg:

sum = 0;
n = 1; 
while(n <= 10)
{
    sum = sum + n* n;
    n = n + 1;
}
printf(“sum = %d \n”,sum);

The Do – While Statement

In while loop the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. Such situations can be handled with the help of the do statement.

do 
{
body of the loop ;
}
while(test condition);

Since the test-condition is evaluated at the bottom of the loop, the do…..while construct provides an exit-controlled loop and therefore the body of the loop is always executed at least once.

Eg:

do 
{ 
printf(“Input a number\n”); 
number = getnum();
} 
while(number > 0);

The for Statement

The for loop is another entry-controlled loop that provides a more concise loop control structure. The general form of the for loop is

for(initialization ; test-condition ; increment 
{ 
 body of the loop ;
}

The execution of the for statement is as follows:

Initialization of the control variables is done first. The value of the control variable is tested using the test-condition. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.

When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the control variable is either incremented or decremented as per the condition.

Eg :

for(x = 0; x <= 9; x = x + 1) 
{ 
printf(”%d”,x); 
} 
printf(“\n”);

The multiple arguments in the increment section are possible and separated by commas.

Eg:

sum = 0; for(i = 1; i < 20 && sum <100; ++i) { sum =sum + i; printf(“%d %d \n”,sum); }

Nesting of For Loops

C allows one for statement within another for statement.

for(i = 1; i < 10; ++ i) 
{ 
for(j = 1; j! = 5; ++j) 
{ 

}
}
Please log in to add an answer.