Cute FTP Pro

For Loops in Depth


The following topics are covered in this section:


Statement and Expression

A statement in C++ refers to a part of the code that is terminated in a semicolon. It is the smallest part of the program that can be executed. For example:

sum = a + b;

is a statement. A C++ program will consist of a set of statements.

An expression is a grouping of variables, constants, function calls and operators (arithmetic, logical, relational) to return a value. In the above example, a + b is an expression.

While dealing with control mechanisms you will come across blocks of instructions. A block of instruction refers to a set of statements grouped together within a block. The block is identified by using the curly braces ‘{‘ to start the block and ‘}’ to end of the block.

Program flow and control: 

What is program flow? Whenever we write a program we have to decide on the sequence of operations that the program has to perform. Generally this is represented in the form of an algorithm. Writing algorithms for simple programs might seem trivial but when you write complex programs, the algorithm helps reduce programming errors. Let’s take a look at a simple algorithm to calculate the average weight of 3 persons: 

Step 1: Start the program.

Step 2: Obtain the weight of all 3 persons (in weight1, weight2, weight3).

Step 3: Calculate the average weight as average = (weight1 + weight2 + weight3)/3

Step 4: Display the result

Step 5: Stop the program  

By looking at the algorithm a programmer can easily write the entire program. When you have a complex program, if you have written an algorithm then you can eliminate potential logical errors in this stage itself.

In the algorithm we define the way in which the program control should flow. First the program should get the 3 inputs from the user, then it should calculate the value for average and finally it should display the result. Thus we can say that the program flow has been clearly defined. But program flow needn’t always be so simple. You might need to take some decisions and alter program flow.  

Control refers to that part of the program which is currently being executed. Let’s write an algorithm to divide 2 numbers obtained from the user. 

Step 1: Start the program.

Step 2: Obtain the 2 numbers (num and den) from the user.

Step 3: Check if den is zero. If it is then go to step 4 else go to step 5.

Step 4: Display “Denominator is zero. Cannot perform division”. Go to step 7.

Step 5: Calculate the quotient by dividing num by den.

Step 6: Display the result.

Step 7: Stop the program.

In this example, there are 2 routes the program can take. If the user enters the denominator as 0 then the error should be produced else normal division should be performed.

The pictorial representation of an algorithm is called a flowchart.

Loops

Suppose you want to add the numbers from 1 to 10, what would you do? Of course you could write a long statement that would calculate 1+2+3+4+…+10. What if 10 were changed to 100 or 1000? Whenever there are statements to be repeated you can make use of loops (in fact you should make use of loops). When using loops, some condition should be specified so that the loop will terminate (otherwise the set of statements within the loop will keep executing infinitely).


For loop statement

For loop is used for performing a fixed number of iterations (or repetitions).

The syntax is:

The ‘for’ loop has three expressions that have to specified.

Initialize variables: This expression is executed only once (when the program flow enters the loop for the first time). It is usually used to assign the loop variable an initial value.

Condition to test: involves relational operators. It is executed each time before the body of the loop is executed. Only if the condition is true will the loop body be executed. If it is false then the loop is terminated and the control passes to the statement following the ‘for’ loop body.

Assign new value to variable: It is executed at the end of every loop after the loop body. Usually it is used for assigning a new value to the loop variable.

Example:

                      // To find square of numbers from 1 to 10

        #include <iostream.h>
        int main( )
        {
        int var;
        for (var = 1 ; var<=10; var++)
        {                                                                       //beginning of ‘for block’
        cout<< "Square of "<<var<< "is" <<var * var;
        }
        return 0;                                                 // Statement after the ‘for’ loop body.
        }

       

In this program, ‘var’ is the loop variable. The loop variable controls the loop. We have initialized this variable to1. The condition that is to be tested before executing the loop each time is:

Is ‘var’ less than or equal to 10 (i.e. var<=10)?

Thus each time var satisfies the above condition the loop body will be executed. ‘var’ is re-initialized with a value at the end of every loop using the expression:

var++

(i.e. incrementing the value of var by 1 each time the body of the loop is executed).

So, to put the program flow in sequence, it would be as follows:

Initially ‘var’ is assigned a value of 1. The condition is tested. Since 1 is less than 10, the body of the loop is executed. In the body of the loop we display the square of var (in this case it is the square of 1). With this, the loop has completed one cycle. In programming terms this is called as ‘one iteration’. The variable ‘var’ is then assigned a new value depending on what is specified in the ‘for loop’. In this program we have written:

var++

Thus ‘var’ is incremented by one. Now, the new ‘var’ value is 2. Again 2 is less than 10 and so the body is again executed with the ‘var’ value as 2. This will be the second iteration.

This process is repeated until ‘var’ becomes 10. When ‘var’ is 10, the condition is again tested. Since 10 is equal to 10 the condition will return a true value (meaning that the condition is satisfied). The loop body is executed again. For the next iteration, ‘var’ is 11. But since 11 is greater than 10 the condition to test returns a false value and the loop body terminates. Program flow goes to the line after the ‘for loop’ body. In this case, it happens to be return 0 (which signals the end of the program).

Beware:

When you make use of relational operators be careful that you do not leave a whitespace between < and =. You should write the coding as:

<= and not as < =


More on ‘for’ Loops

We've seen the usual ‘for loop’ but there are some interesting modifications to the ‘for loop’. The normal syntax for the ‘for loop’ is:

Have you wondered what will happen if we don't specify one of the three parts of the ‘for loop’?

        #include <iostream.h>
        int main( )
        {
            int i = 2;
            for ( ; i<8 ; i++ )                   // No initialization of loop variable!
            {
                cout<<i;
             }
            return 0;
        }

The ‘for loop’ does not have any initialization expression. Will it run? Yes it will because 'i' has been initialized outside the ‘for’ loop. This is perfectly valid and the output would be:

234567

But if you don't specify i = 2 and try to compile the program, the program would still run (but you won't know what value of ‘i’ has been assumed by the compiler). Thus the initialization expression can be left out in a ‘for’ loop if you have initialized the variable with a value before entering the ‘for loop’.

Basically, it is not a must that we have to specify all the 3 parts in a ‘for’ loop. Check out the following program:

        #include <iostream.h>
        int main( )
        {
            int i;
            for ( i = 1; i != 2 ; i++ )
            {
                cout<<i;
            }
            return 0;
        }

What do you think the output will be?

The output will be:

1

‘i’ starts from 1, when it goes to the value 2 the condition i != 2 becomes false (because ‘i’ is now equal to 2). Whenever the condition becomes false the ‘for’ loop will immediately terminate.

Suppose instead of

for ( i = 1; i != 2 ; i++ )

we had coded as

for ( i = 2; i != 2 ; i++ )

what will happen? Simple, the ‘for’ loop will be terminated instantaneously; in other words the program will not enter the ‘for’ loop even once because the condition becomes false in the first test itself.

Another variation of the for loop is shown below:

This is called an infinite loop. If you're wondering why one would want an infinite loop; well, you can use it to create time delays or you could specify some condition within the loop to cause it to break out of the loop. Breaking out from a for loop (or an infinite for loop) can be accomplished by using a ‘break’ statement (this will be discussed later).

So far we’ve seen ‘for loops’ using only one loop variable. But you can have ‘for loops’ with two loop variables as well.

        #include <iostream.h>
        int main( )
        {
            int x,y;
            for (x=1,y=1; x<10,y<5 ; x++,y++)
            {
                cout<<"\n"<<x<<y;
            }
            return 0;
        }

Here we’ve made use of two ‘for’ loop variables (x and y). Both are initialized to 1. There are two conditions specified:

x<10, y<5

This actually means that x should be less than 10 and y should be less than 5. If both are satisfied then the loop body will be executed. If even one isn’t satisfied the loop will terminate.

The output will be:

Remember: You have to make use of comma (,) to say that you want to initialize x to 1 and y to 1. It is a comma and not a semi-colon (many beginners use the comma and semi-colon interchangeably). Semi colon is used in the ‘for’ loop to separate each of the expressions (to separate the 3 parts of a ‘for’ statement: the initialize, test and re-initialize parts).

You might wonder whether you could use more than two loop variables? The answer is yes. You can use more loop variables but usually you won’t need to use more than 2.

Empty ‘for’ loops: If the ‘for’ loop has no body to execute then it is called an empty ‘for’ loop. For example:

for (int j=0; j<100; j++);

The ‘for’ loop has been terminated by the semi-colon. This ‘for’ loop has no body and it will simply keep incrementing the value of ‘j’ from 0 to 100. This can be used to produce any required delay (because the loop has to be repeated 100 times). Delays can be useful in I/O operations or even while displaying (if the output is appearing too fast).


Body of the ‘for’ loop

The body of the ‘for’ loop is the statement that immediately follows the ‘for’ statement if the body of the loop hasn’t been enclosed within braces. For example:

for ( j = 0; j<10; j++)
cout<< "hi";
cout<< j ;

The compiler will only consider the statement:

cout<< "hi";

as belonging to the ‘for’ loop body. Hence the above code fragment would print "hi" ten times and the value of ‘j’ will only be printed once. The above set of statements is equivalent to:

for ( j = 0; j<10; j++)
{
cout<< "hi";
}
cout<< j ;

It is good programming practice to clearly specify the body of loops using braces (the same holds good for ‘while’ loops and ‘if’ statements).


Nesting ‘for’ Loops

The term nesting is frequently used in programming languages. Nesting means one within the other. For example: when we say nesting of ‘for loops’ it means that there is one ‘for loop’ within the body of another ‘for loop’.

You might wonder as to how the program executes in the case of two ‘for loops’. Let’s assume that the outer ‘for loop’ has a loop variable ‘j’ that takes values from 1 to 10 in increments of one. Let the second loop variable be ‘k’ assuming values from 1 to 20.

Thus initially j=1, and the program will encounter the second ‘for loop’. Now k=1 and the body of the second (inner) loop is executed. Then k is incremented to 2 (while j is still at 1) and the inner loop is executed again. Next k=3 while j is still 1 and the inner loop is executed once more. When the ‘k’ value reaches 20, the inner loop terminates and only then will ‘j’ be incremented to 2. Again for a ‘j’ value of 2, the inner loop will be repeated 20 times (since k will take values from 1 to 20) and so on.

How many iterations are performed totally? A total of 10 * 20 (=200) iterations are performed using these two ‘for loops’.


Go back to the Contents Page


Copyright © 2004 Sethu Subramanian All rights reserved.