Coupon Accepted Successfully!


The for Loop

The for loop allows one to execute a set of the instructions until a condition is met. The condition may be predefined or open-ended. Although all programming languages provide for loops still the power and flexibility provided by C/C++ is worth mentioning. The general syntax for the for loop is as follows Figure.

for loop

An example of the for loop is as shown in Figure.

The for loop

Although many variations of for loop are allowed but the simplest form is as shown in Figure 3.

The ‘initialization’ is an assignment statement that is used to set the loop control variable(s). The ‘condition’ is a relational expression that determines the number of the iterations desired or the condition to exit the loop. The ‘increment’ or the re-evaluation parameter decides how to change the state of the variable(s) (quite often increase or decrease so as to approach the limit). These three sections must be separated by semi-colon (;). The body of the loop may consist of a block of statements (which have to be enclosed in braces) or a single statement (enclosure within braces is not compulsory but advised).


Flow chart of for loop is as shown in Figure.

The following programs serve as examples for the for loop.




Flow chart of for loop

6.4 Write a program to display all leap years from 2000 to 2012.

Explanation: One must be aware that only those years that are

  1. divisible by 4 and not 100,
  2. divisible by 100 and also 400

alone are qualified to be called as leap years. The above program checks for these conditions for all years from 2000 to 2012 and then prints the year if it is leap. Stress is on ‘for’ loop construct and use of ‘if’ and ‘else – if’ in the body.

Test Your Skills Now!
Take a Quiz now
Reviewer Name