Why loop control structures Methods of looping C

Using only sequential execution and conditional execution set a limit to the range of problems that can be solved. Even in real life we need to repeat action for a specified number of times .
E.g.

  1. We need to recite a poem again and again if we want to learn it by-heart.
  2. If we have purchased an item on installment basis, period ranging for one year. We need to pay the installments each month (total 12 times).

Loop control structure helps us achieve the same.

Methods of looping

  • While loop
  • For loop
  • Do-while loop

There are 3 methods using which we can repeat any part of the program. The repetitions may be for a fixed number of times or it may be until a certain condition is reached .

While loop

  • Using while loop

The general form of the while-statement is

while (expression)
Statement

The expression following while should be enclosed in round brackets. It is usually a logical expression, which results in true (1) or false (0). The statement following while forms the body of the while loops. Statement can be either a single statement or a compound statement.

The statements are executed as long as the logical expression is true. When the result is false, execution starts at the statement following while loop. There should be a statement in the body of the while loop that will eventually cause expression to become false. When there are no such statements, while loop will be executed forever. This should be avoided as it will cause the program to get stuck.

Using while loop

Example

/* program demonstrates the use of while loop */ /* It accepts the radius from an user and calculates the area of circle as long as user enters 'y'when asked whether to calculate area */ //assuming value of pi is 3

#define PI 3 #include<stdio.h> void main ( ) { char ans; int r,area; printf("n Calculate area of circle? (Enter y or Y)");
scanf("%c", &ans);
while ((ans == 'y') || (ans == 'Y')) /* while loop continues as long as condition is true */
{
printf("n Enter radius of circle ");
scanf("%d", &r);
area = PI * r * r ;
printf("nAREA = %d ", area);
printf("n Calculate area of circle? (Enter y or Y)");
scanf("%c",&ans);
}
}

In this program area of a circle is calculated by getting radius from user, as long as value of variable, ans is ‘y’ or ‘ Y ‘. Once ans has a value other than ‘y’or’Y’, execution starts from statement after while loop. Expression is evaluated each time to get the result.

For loop

  • Using for loop

This is the most commonly used looping statement in ‘C’. The general form of the statement is

For (Expression1; Expression2; Expression3)
Statement;

It contains 3 expressions. Expression1 is used to initialize some parameter called the index or loop counter that controls the looping action. It is an assignment expression.

Expression2 is the condition that must result to true to continue execution in for loop. It is a logical expression.
Expression3 is used to alter value of index. It is a unary or assignment expression.

Using for loop

/* program to demonstrate use of for loop */

#include<stdio.h>
main ( )
{
//j is used as index of for loop.
int j ;
for ( j = 0; j <= 10 ; j ++)
printf (“n value of j = %d”, j) ;
}
Expression1 is (j =0) (Initialization)
Expression2 is (j <= 10) (condition)
Expression 3 is (j ++) (Incrementing)

Value of j is printed as j runs from 0 to 9.

When for loop is executed for the first time j is initialized to 0. Condition (j <= 10) is checked. If it is true printf statement is executed.

At the end j is incremented by 1, with j ++.
The other alternative being j = j = 1 and j += 1.
Again condition j <= 10 is checked. If it is true, printf is executed. This repeats until condition j <= 10, result in false. Here j is the index. Index can be incremented, or decremented by any value (1 is not compulsory).

If it is decremented, initialization of index should be done accordingly.
1st and 3rd expression is omitted, if other statements are provided for initializing the index andor altering the index.

If the second expression is omitted, it will be assumed to have value of 1 and loop will continue indefinitely unless terminated by break or return statement.Any of the three expressions can be omitted, but the semicolons must remain.

Why loop control structures Methods of looping

The same program using while loop will have the following structure
Expression 1;

while (Expression2)
{ statement;
Expression 3;
}
j = 0;
while (j <= 10)
{
printf (“n%d”, j);
j ++;
}

do-while

  • Using do-while loop

do-while is a form of while loop. The general format is

do
Statements
while (expression);

In while and for loop conditional expression is evaluated at the beginning of loop, whereas in do-while loop expression is evaluated at the end of the loop. This causes execution of statements in the loop at least once. Once the loop statements are executed expression is evaluated and depending on its result further action is taken (which is the similar to while loop).

Thus do-while loop is used in places where statements are to be executed at least once irrespective of the conditional expression.

Using do-while loop
Above example can be rewritten using do-while. This will help to understand the difference between while and do-while clearly.

/* program to demonstrate use of do-while loop. Here terminating
condition is checked at the end of loop */
#define PI 3

#include<stdio.h>
#include<conio.h>
main ( )
{ char ans;
int r, area;
do
{
printf ("n Enter radius of circle");
scanf ("%d", &r);
area = PI * r * r;
printf ("AREA = %d", area);
fflush (stdin);
printf ("n Calculate area of circle? (Enter Y or N)");
ans = getche();
}
while((ans == 'y' ) || (ans =='Y'));
}

Here area of circle is calculated at least for one circle.’
*fflush()– The reason for using the function fflush() is that when we use scanf() we accept data from user, the data along with the “enter key” goes into the key board buffer. The scanf() assigns data to the given variable but keeps the ‘enter key’ in the buffer. When the user is prompted for Y/N, this enter key will be provided as a response since getche() requires only one character. To avoid this, fflush() is used. The fflush() flushes out all the remains in the i/p buffer and accepts a fresh input from the user. The parameter passed to fflush() is the buffer we want to flush out. Here stdin() is the buffer related with standard input device the keyboard.

Use while loop or use for loop
Using while or for loop can be a personal choice. But still there is a point to be noted. While-loop is generally used in places where number of iteration are not known and statements are to be executed until a condition is satisfied, though it can be effectively used when number of iterations are known. For-statement is generally used where it is a simple initialization, testing and incrementing values.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics