for loop

Purpose

The program will execute one or more statements a particular, known number of times.

General Structure of for loops

	for ( initialize loop control variable ; 
		repetition condition for loop control variable; 
		update of control variable )
	{

	   one or several statements. Very often the loop control variable
	   is used here. It is extremely dangerous, but no illegal, to
	   change its value inside the for-loop.

	}

The loop control variable is usually an ordinary variable of type integer. Floating type variables are legal but very dangerous because of round-off errors.

After the loop has continued as determined by the initialization, repetition and update items the program will continue with the statements below the loop.

Example

Adding the numbers 1 through n.
	int i , n , sum ;
		
	n   = 5 ;  
	sum = 0  ;
	for ( i=1 ; i <= n ; i++ )
	{
	   sum = sum + i ;
	}

	cout << "Sum of 1+2+ ... " << n << "equals " << sum << endl ;

Initialization of control variable : i=1

Repetition condition : i <= n

Update : i++ ( same as i = i + 1 )

All three items - initialization, repetition , and update - can assume as complicated a form as one wishes depending on what you - as the designer of a program - wants to achieve. The repetition condition is always of the form of a logical expression.

The break statement

At time the problem arises that you wish to terminate when a certain condition is met while the program is somewhere in the middle of statements inside a for-loop and you wish to terminate the loop immediately. The break-statement allows you to do just that.

An example :

	for ( i=1 ; i <= 10 ; i=i+2 )
	{
	    cout << "Give integer n ( =0 to stop ) : " ;
	    cin >> n ;
	    if ( n == 0 )
	    {
		break ;
	    }
	    .... do stuff with n
	}

In this example the for-loop would run 10 times, unless the user answers the request for an integer with the number 0. If that happens the for-loop will be terminated immediately and continues with statements ( not shown ) below the for-loop.

Last revised: 08/23/13