Lesson-7 Branching and Looping

7.1 INTRODUCTION

The programs that we have developed so far used either a sequential or a decision control instruction. In the first one, the calculations were carried out in a fixed order, while in the second, an appropriate set of instructions were executed depending upon the outcome of the condition being tested (or a logical decision being taken).

These programs were of limited nature, because when executed, they always performed the same series of actions, in the same way, exactly once. Almost always, if something is worth doing, it’s worth doing more than once. You can probably think of several examples of this from real life, such as eating a good dinner or going for a movie. Programming is the same; we frequently need to perform an action over and over, often with variations in the details each time. The mechanism, which meets this need, is the ‘loop’, and loops are the subject of this chapter.

7.2 Loops

The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control instruction.

There are three methods by way of which we can repeat a part of a program. They are:

  1. Using a while statement

  2. Using a do-while statement

  3. Using a for statement

A program loop therefore consists of two segments:

  • Body of the loop

  • control statement

The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop. In looping process in general would include the following four steps:

  1. Setting and initialization of a counter

  2. Execution of the statements in the loop

  3. Test for a specified conditions for the execution of the loop

  4. Incrementing the counter

7.2.1 While Statement

When in a program a single statement or a certain group of statements are to be executed repeatedly depending upon certain test condition, then while statement is used.

The syntax is as follows:

while (test condition)

{

body_of_the_loop;

}

Here, test condition is an expression that controls how long the loop keeps running. Body of the loop is a statement or group of statements enclosed in braces and are repeatedly executed till the value of test condition evaluates to true. As soon as the condition evaluates to false, the control jumps to the first statement following the while statement. If condition initially itself is false, the body of the loop will never be executed. While loop is sometimes called as entry-control loop, as it controls the execution of the body of the loop depending upon the value of the test condition. This is shown in the figure 7.1 given below:

Figure 7.1

Figure 7.1: The while loop statement

Let us consider a program to illustrate while loop,

Write a program to calculate the factorial of a given input natural number.

/* Program to calculate factorial of given number */

#include <stdio.h>

#include <math.h>

#include <stdio.h>

void main( )

{

int x;

long int fact = 1;

printf(“Enter any number to find factorial:\n”); /*read the number*/

scanf(“%d”,&x);

while (x > 0)

{

fact = fact * x; /* factorial calculation*/

x=x-1;

}

            printf(“Factorial is %ld”,fact);

}

7.2.2 The do...while Loop

There is another loop control structure which is very similar to the while statement – called as the do.. while statement. The only difference is that the expression which determines whether to carry on looping is evaluated at the end of each loop. The syntax is as follows:

do

{

statement(s);

} while(test condition);

In do-while loop, the body of loop is executed at least once before the condition is evaluated. Then the loop repeats body as long as condition is true. However, in while loop, the statement doesn’t execute the body of the loop even once the condition is false. That is why do-while loop is also called exit-control loop. This is shown in the figure 7.2 given below.

Figure 7.2

Figure 7.2: The do…while statement

Let us consider a program to illustrate do..while loop,

Write a program to print first ten even natural numbers.

/* Program to print first ten even natural numbers */

#include <stdio.h>

void main()

{

int i=0;

int j=2;

do

{

printf(“%d”,j);

j =j+2;

i=i+1;

} while (i<10);

}

OUTPUT

2 4 6 8 10 12 14 16 18 20

7.2.3 The for Loop

for statement makes it more convenient to count iterations of a loop and works well where the number of iterations of the loop is known before the loop is entered. The syntax is as follows:

for (initialization; test condition; increment or decrement)

{

Statement(s);

}

The main purpose is to repeat statement while condition remains true, like the while loop. But in addition, for provides places to specify an initialization instruction and an increment or decrement of the control variable instruction. So this loop is specially designed to perform a repetitive action with a counter.

The for loop as shown in figure 7.3, works in the following manner:

  • Initialization is executed. Generally it is an initial value setting for a counter variable. This is executed only once.

  • Condition is checked, if it is true the loop continues, otherwise the loop finishes and statement is skipped.

  • Statement(s) is/are executed. As usual, it can be either a single instruction or a block of instructions enclosed within curly brackets { }.

  • Finally, whatever is specified in the increment or decrement of the control variable field is executed and the loop gets back to step 2.

Figure 7.3

Figure 7.3: The for statement

Let us consider a program to illustrate for loop,

Write a program to print first n natural numbers.

/* Program to print first n natural numbers */

#include <stdio.h>

void main( )

{

int i,n;

printf(“Enter value of n \n”);

scanf(“%d”,&n);

printf(“\nThe first %d natural numbers are :\n”, n);

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

{

printf(“%d”,i);

}

}

OUTPUT

Enter value of n

6

The first 6 natural numbers are:

1 2 3 4 5 6

The three statements inside the braces of a for loop usually meant for one activity each, however any of them can be left blank also. More than one control variables can be initialized but should be separated by comma.

Various forms of loop statements can be:

(a).          for(;condition;increment/decrement)

               body;

A blank first statement will mean no initialization.

(b).          for (initialization;condition;)

               body;

A blank last statement will mean no running increment/decrement.

(c).          for (initialization;;increment/decrement)

               body;

A blank second conditional statement means no test condition to control the exit from the loop. So, in the absence of second statement, it is required to test the condition inside the loop otherwise it results in an infinite loop where the control never exits from the loop.

(d).          for (;;increment/decrement)

               body;

Initialization is required to be done before the loop and test condition is checked inside the loop.

(e).          for (initialization;;)

               body;

Test condition and control variable increment/decrement is to be done inside the body of the loop.

(f).           for (;condition;)

               body;

Initialization is required to be done before the loop and control variable increment/decrement is to be done inside the body of the loop.

(g).          for (;;;)

               body;

Initialization is required to be done before the loop, test condition and control variable increment/decrement is to be done inside the body of the loop.

7.2.4 The Nested Loops

C allows loops to be nested, that is, one loop may be inside another. The program given below illustrates the nesting of loops.

Let us consider a program to illustrate nested loops,

Write a program to generate the following pattern given below:

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

/* Program to print the pattern */

#include <stdio.h>

void main( )

{

int i,j;

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

{

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

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

{

printf("%d\t",j);

                                    }

}

}

Here, an inner for loop is written inside the outer for loop. For every value of i, j takes the value from 1 to i and then value of i is incremented and next iteration of outer loop starts ranging j value from 1 to i.

Last modified: Monday, 28 October 2013, 4:28 AM