Module 3. Control statements

LESSON 12

Loop Control STATEMENTS – Part II

(Nesting of Control Statements)

12.1  Nesting Decision and Loop Control Statements

Nesting means embedding one object in another object. Nesting is quite common in ‘C’ structured programming, where different logic structures, viz., sequence, selection and repetition are combined (i.e., nested in one another), usually indicated through different indentation levels within the source code as delineated through the following code segments:

Illustration 1:
main()
{
  int row, col, sum ;
  for (row = 1; row <= 3; row++) /* outer loop */
  {
    for (col = 1; col <= 2; col++) /* inner loop */
    {
       sum = row + col ;
       printf ("row = %d column = %d sum = %d\n", row, col, 

               sum);
    }
  }
  return 0;
}
Output: 
row = 1 column = 1 sum = 2
row = 1 column = 2 sum = 3
row = 2 column = 1 sum = 3
row = 2 column = 2 sum = 4
row = 3 column = 1 sum = 4
row = 3 column = 2 sum = 5
Explanation

In this illustration, for each value of the variable row in the inner loop is iterated twice, with the variable col taking on values from 1 to 2. The inner loop terminates when the value of col exceeds 2, and the outer loop terminates when the value of row exceeds 3. Evidently, the body of the outer for loop is indented, and the body of the inner for loop is further indented. These multiple indentations make the programme reading easy for better understand the logic. Instead of using two statements, one to calculate sum and another to print it out, we can integrate this into a single statement as follows:

printf ("row = %d column = %d sum = %d\n", row, col, row+col);
The way for loops have been nested here, similarly, two while loops can also be nested. Also, for loop is possible to be nested within a while loop and vice-versa.

Illustration 2: The following code segment demonstrates nesting of decision control structure within loop control structure.

int i;

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

{

if(i==5)

   break;

else

   printf(“%d”, i);

}

printf(“Hello”);

Output:

1234Hello

In this illustration, within the ‘for’ loop, int type variable ‘i’ is initialised with value as ‘1’ having upper limit ‘10’; and is incremented by 1 when the underlying condition is satisfied. In the ‘if’ statement, the condition is checked that i==5 or not, if TRUE, the ‘break’ statement is executed and control passes to the next statement out of the loop, showing the output: Hello. Otherwise, the ‘else’ statement will be executed thereby printing the value of ‘i’; followed by incrementing value of ‘i’ by 1 and so on until value equals to 5 or condition gets FALSE.

Example 1: Ohm’s law is I = V/R ; write a programme to calculate I from given n sets of V and R.

#include <stdio.h>

#include <conio.h>

void main()

{

   clrscr();

   int n, k;

   float i, v, r;

   printf("\nEnter number of sets ");

   scanf("%d", &n);

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

   {

     printf("\nEnter values for potential differenc(V) and 
            resistance (R) ");

     scanf("%f %f", &v, &r);

     i=v/r;

     printf("\n V = %5.2f;  R = %5.2f; and I = 
             %0.2f.", v, r, i);

     printf("\n");

   }

   getch();

}

Example 2: Write a programme, which can input a positive integer (<=10000000) and prints it in reverse order, for example, 9875674 to 4765789.

#include <stdio.h>

#include <conio.h>

void main()

{

  clrscr();

  long int num, mod, rev=0;

  printf("Enter the number");

  scanf("%ld", & num);

  while(num>0)

  {

    if(num<=10000000)

    {

       mod=num%10;

       rev=(rev*10)+mod;

       num=num/10;

    }

    else

    break;

  }

  printf("Reverse Number is : %ld", rev);

  getch();

          }

Output:

Enter the number 9875674

Reverse Number is : 4765789

An exercise for students

Write a programme to calculate sum of squares of all odd integers between 17 and 335; exclude integers divisible by 7.

Example 3: Programme corresponding to the algorithm described in Example-3 under Lesson-1 to find and print the largest number among any n given numbers.  

/*    c program for Example 3, Lesson 1      */

#include <stdio.h>

void main()

{

 int n, current_number, next_number, max, counter=1;

 printf("\nEnter values for n and current number: ");

 scanf("%d %d", &n, &current_number);

 max = current_number;

 while (counter < n)

 {

     counter = counter + 1;

     printf("\nEnter next number: ");

     scanf("%d", &next_number);    

     if(next_number > max)

        max = next_number;

 }

   printf("\nThe largest number is : %d", max);

}

Test Output:

Enter values for n and current number: 5 30

Enter next number: 90

Enter next number: -1

Enter next number: 99

Enter next number: 87

The largest number is : 99

Example 4: Write a programme equivalent to the algorithm given in Exercise-8 under Lesson-1 to calculate sum of squares of a given set of numbers; and test the programme with input values for the variables n and val as 5; and 6, 12, 24, 48 and 96, respectively.

/*  ‘C’ programme for Exercise-8 of Lesson-1  */

#include <stdio.h>

void main()

{

 int n, i=1;

 long float val, ssq=0;

 printf("\nEnter n : ");

 scanf("%d", &n);

 while (i<=n)

 {

     printf("\nEnter val : ");

     scanf("%lf", &val);

     ssq = ssq + val*val;

     i=i+1;

 }

 printf("\nSum of squares :%lf", ssq);

}

Output:

Enter n : 5

Enter val : 6

Enter val : 12

Enter val : 24

Enter val : 48

Enter val : 96

Sum of squares :12276.000000

Example 5: Programme to check whether a given number is prime number?

You know that a prime number is a natural number, which is divisible by 1 and itself.
#include <stdio.h>
#include <conio.h>
void main()
{
  int num,i,z;
  printf("Enter the value of num");
  scanf("%d",&num);
  i= 2;
  while (i < num)
  {
    if(num%i==0)
    {
      z=1;
  }
  i=i+1;
}
printf("After checking the result is\n");
if(z== 1)
{
printf("Given number is not prime number");
}
else
{
printf("Given number is prime number");
}
getch();
}

Test Output

Enter the value of num 7
After checking the result is
Given number is prime number

12.2 continue Statement

The continue statement is just opposite to the break statement, i.e., unlike the break statement that terminates the loop, the continue statement immediately loops again thereby skipping the rest of the code. It works only within loops where its effect is to force an immediate jump to the loop control statement. Like a break, continue should be protected by an ‘if’ statement.

Illustration

Consider the following code segment to comprehend the continue statement.

int i;

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

{

if(i==5)

continue;

else

printf(“%d ”, i);

}

printf(“\nNote that fifth value of i is not printed!”);

The above code displays the following information (which is self explanatory) on the output device:

1

2

3

4

6

7

8

9

10   

Note that fifth value of i is not printed!