Module 3. Control statements

Lesson 11

Loop Control STATEMENTS – PART I

(while, do...while and for Loops)

11.1  Loops

Besides decision control statements as described in previous Lesson-10, the other main types of control statement are the iterative statements that are used to create looping mechanism. Thus, loops allow a statement (or block of statements) to be repeated until a given criterion is fulfilled. ‘C’ facilitates three types of loop:

a) while

b) do…while

c) for

11.2 while Loop

The while loop keeps repeating an action until a condition gets false. This looping statement is useful where the programmer does not know beforehand as to how many times the loop will be executed. The general syntax is:

while (expression)

{

    Statements;

}

Example 1: Programme to generate even series from 1 to 50 using while loop.

int i = 2;

while (i <= 50)

{

printf(“%d\t”, i);

i = i + 2;

}

In this example, ‘i’ considered as an integer type loop-variable, which is initialised with value, ‘0’. In the while loop, first of all the underlying criterion is checked, i.e., whether the value of ‘i’ is less than or equal to 50; if TRUE, the control will enter in the loop and keeps on updating the loop-variable ‘i’ and prints the output. Once the condition gets FALSE, the control will pass to the next statement out of the loop. The above code segment will print the following result:

2

4

6

8

10

12

14

16

18

20

22

24

26

28

30

32

34

36

38

40

42

44

46

48

50

 

 

 

 

 

Example 2: Programme to evaluate the given series, ; to calculate  . 

Also, it compares the calculated value with the one by using inbuilt library function.

//C programme to find sum of cosine series?

#include <stdio.h>

#include <conio.h>

#include <math.h>

void main()

{

  clrscr();

  float power = 2.0, numr, denr = 1.0, x1, sum;

  int i = 1, n, s = -1, x;

  printf("\n\n\t ENTER THE ANGLE...: ");

  scanf("%d", &x);

  x1 = 3.142 * (x / 180.0);

  sum = 1.0;

  numr = x1*x1;

  printf("\n\t ENTER THE NUMBER OF TERMS...: ");

  scanf("%d",&n);

  while(i<=n)

  {

    denr = denr * power * (power - 1.0);

    sum = sum + (numr / (denr * s));

    s = s * (-1);

    power = power + 2.0;

    numr = numr * x1 * x1;

    i++;

  }

  printf("\n\t THE SUM OF THE COSINE SERIES IS : %0.5f", sum);

  printf("\n\n\t THE VALUE OF COSINE FUNCTION FOR ANGLE = %d IS :

  %0.5f",x,cos(x1));

  getch();

}

Let us input the angle as 5 radians and number of terms for iteration as 10. Then, the above programme produces the following output:

ENTER THE ANGLE...: 5

 

ENTER THE NUMBER OF TERMS...: 10

 

THE SUM OF THE COSINE SERIES IS : 0.99619

 

THE VALUE OF COSINE FUNCTION FOR ANGLE = 5 IS : 0.99619

 

Example 3: Programme corresponding to the algorithm given in Example-1(b) under Lesson-1 to compute average of n numbers using while loop.

#include <stdio.h>

void main()

{

 float x, sum=0.0;

 int n, i=1;

 printf("Enter value for n: ");

 scanf("%d", &n);

 while (i<=n)

 {

   printf("Enter value for x: ");

   scanf("%f", &x);

   sum=sum+x;

   i=i+1;

 };

 mean = sum/ n;

 printf("\nMean =%5.2f", mean);

}

Test Output:

Enter value for n: 5

Enter value for x: 10

Enter value for x: 10.5

Enter value for x: 12.12

Enter value for x: 13.45

Enter value for x: 23.90

Mean=13.99

Example 4: Programme corresponding to the algorithm given in Example-2, Lesson-1 to input an examination’s marks of n students as well as to test each student’s marks for the award of a grade.

#include <stdio.h>

void main()

{

 int n, marks, i=1;

 printf("\nEnter value for n : ");

 scanf("%d", &n);

 while (i<=n)

 {

    printf("\nEnter eaxm's marks : ");

    scanf("%d", &marks);

    if (marks >= 80)

       printf("\nDistinction");

    else if (marks >= 60 && marks < 80)

       printf("\nMerit");

    else if (marks >= 40 && marks < 60)

       printf("\nPass");

    else if (marks < 40)

       printf("\nFail");

    i=i+1;

 }

}

Test Output:

Enter value for n : 5

Enter eaxm's marks : 92

Distinction

Enter eaxm's marks : 67

Merit

Enter eaxm's marks : 56

Pass

Enter eaxm's marks : 32

Fail

Enter eaxm's marks : 71

Merit

11. 3  do…while Loop

The do…while loop is very similar to the while loop except that the condition is tested at the end of the loop body. This ensures that the loop is executed at least once. Provided that the underlying criterion is TRUE, the loop statement(s) are repeated. The general syntax is:

do

{

   statements;

}

while (expression);

Note that the statements underlying a while loop might never be executed if the expression is false; however, a do…while statement will always execute the statements contained within the body of the loop at least once.

Illustration – Consider the following code segment:

int  i = 1;

do

{

    printf(“I like computer programming!”);

    ++i;

}

while (i <= 7);

In this code segment, the statements inside the loop are executed at least once without any consideration for the underlying criterion; as a result the slogan “I like computer programming” is printed during the first iteration. Thereafter, the conditional expression is evaluated; and if it is found to be FALSE, it will not execute the block of statements any more and exits the loop thereby transferring the control to the next statement.

Example 5: Programme to calculate the resultant focal length : f , when f1 and  f2  are placed in contact; use formula;

           
compute for following pairs of focal lengths:

           

           

#include<stdio.h>

#include<conio.h>

void main()

{

float f=0.0, f1=-10.0, f2=-0.5;

clrscr();

do

{       if(f1!=0.0&&f2!=0.0)

        {

          f=(f1+f2)/(f1*f2);

          printf("\nf1, f2 and f values are %5.2f, %5.2f 
                  and %7.3f",f1, f2, f);

          f1=f1+2.0;

          f2=f2+0.1;

        }

        else

        {

          f1=f1+2.0;

          f2=f2+0.1;

          f=(f1+f2)/(f1*f2);

printf("\nf1, f2 and f values are %5.2f, %5.2f 
                  and %7.3f",f1, f2, f);

          f1=f1+2.0;

          f2=f2+0.1;

        }

}while(f1!=12.0&&f2!=0.6);

getch();

}

Example 6: Programme equivalent to algorithm described in Example-1(c) under Lesson-1 to compute average of n numbers using do…while (repeat…until) loop.

#include <stdio.h>

void main()

{

 float x, sum=0.0;

 int n, i=1;

 printf("Enter value for n: ");

 scanf("%d", &n);

 do

 {

   printf("Enter value for x: ");

   scanf("%f", &x);

   sum=sum+x;

   i=i+1;

 } while (i<=n);

 mean = sum/ n;

 printf("\nMean =%5.2f", mean);

}

Test Output:

Enter value for n: 5

Enter value for x: 10

Enter value for x: 10.5

Enter value for x: 12.12

Enter value for x: 13.45

Enter value for x: 23.90

Mean=13.99

11.4  for Loop

The for loop is useful when the number of iterations of the loop is known before the loop is executed. The head of the ‘for’ loop comprises of three constituents separated by semicolons. The general syntax is:

for (initial statement; conditional expression; loop statement)

{

body of the loop ;

}

§  The initial statement is used to initialise the loop variable

§  The conditional expression is used to check whether or not the loop is to be continued again

§  The loop statement is used to change the loop-variable value for further iteration.

Note that all the three constituents are optional; hence, the following typical for statement is valid that forms an infinite loop to display the message “Hello, this is an infinite loop!” repeatedly, as the conditional expression is always considered as TRUE, if the same is absent).

   for (;;)

   {

     printf("Hello, this is an infinite loop!\n");

   }

This will keep on executing the underlying printf statement forever until interrupted by some other means. This might be done so by incorporating either a return or a break statement inside the loop after printf statement.

Example 7: Programme corresponding to the algorithm given in Exercise-7 under Lesson-1?

/*    c programme for Exercise-7, Lesson-1      */

#include <stdio.h>

void main()

{

   int n;

   for (n = 1; n <= 4; n++)

   printf("\n\nLoop%d", n);

}

Output:

Loop1
Loop2
Loop3
Loop4

Example 8: Programme to write a table of 2 using for loop.

#include <stdio.h>

void main()

{

int a=0;

int i;

for ( i=1; i<=10; i++)

{

   a = 2 * i;

   printf(“ %d”,a);

}

}

Here, ‘a’ and ‘i’ are int type variables. Within for loop first step is to initialise ‘i’ with value ‘1’and then condition is checked that its value is less than or equal to ‘10’, if TRUE, statements within the body of the loop are executed and the value of ‘i’ is incremented by ‘1’. Once again, the condition is checked; if it is found valid, the statements within the body of the loop are executed and so on until the condition becomes FALSE. As a result, the following table is displayed on the output device:

2

4

6

8

10

12

14

16

18

20

 Example 9: Programme equivalent to the algorithm given in Example-1(d) under Lesson-1 to compute average of any ten numbers using for loop.

/*    c programme to sum 10 numbers using for loop*/

#include <stdio.h>

void main()

{

int i;

float x, mean, sum = 0.0;

for  (i=1; i<=10; i++)

{

   printf("\nEnter value for x: ");

   scanf("%f", &x);

   sum = sum + x;

}

mean = sum/10.0;

printf("\nMean =%5.2f", mean);

}

Test Output:

Enter value for n: 5

Enter value for x: 10

Enter value for x: 10.5

Enter value for x: 12.12

Enter value for x: 13.45

Enter value for x: 23.90

Mean=13.99