Home »
C/C++ Zone » Looping
Introduction
We have seen in the previous chapter that it is possible to execute a segment
of a program repeatedly by introducing a counter and letter testing it using
the if statement. While this method is quite satisfactory for all practical
purposes, we need to initialize and increment a counter and test its value at
an appropriate place in the program for the completion of the loop. for example,
suppose we want to calculate the sum of square of all integers between 1 and 10.
We can write a program using the if statement as follows:
sum = 0;
n = 1;
loop:
sum = sum + n*n;
if (n == 10)
goto print;
else
{
n = n+1;
goto loop;
}
print:
n = 1;
loop:
sum = sum + n*n;
if (n == 10)
goto print;
else
{
n = n+1;
goto loop;
}
print:
This program does the following thing:
1. Initializes the variable n.
2. Computes the square of n and it to sum.
3. Tests the value of n to see whether it is equal to 10 or not. if it is equal to 10, then the program prints the result
4. If n is less then 10, then it is incremented by one and the control goes back to compute the sum again.
A looping process, in general, would include the following four types:
1. Setting and initialization of a condition variable.
2. Execution of the statement in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
The test may be either to determine whether the loop has been repeated the specified number of times or to determine whether the loop has been repeated the specified number of times or to determine whether a particular condition has been met.
The C language provides for there constructs for performing loop operation. They are:
1. The while statement.
2. The do statement.
3. The for statement.
THE WHILE STATEMENT
The simplest of all the looping structures in C is the while statement. We have used while in many of our earlier programs. 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 repeated execution of the body continues with the statement immediately after the body of the loop.
We can rewrite the program loop discussed in section 6.1 as follows:
sum = 0;
n = 1;
while (n <= 10)
{
sum = sum + n * n;
n = n + 1;
}
printf ("sum = %d\n", sum);

