CS110 Lab: For Loop


The for statement is a looping structure designed specifically to simplify the implementation of count-controlled loops (That is, a count-controlled While loop can be replaced by a For loop.). The loop-control variable, the beginning value, the ending value, and the incrementation are explicitly part of the For loop heading itself.

The syntax template for a For statement is

for (InitStatement; Expression1; Expression2)
   {
	Statement;
   }
Usually, the InitStatement initializes a loop control variable. Expression2 increments or decrements the loop control variable. Expression1 is equivalent to a While condition.

The following For loop reads 10 marks and sums them up.

int sum = 0;
for (int counter = 1; counter <= 10; counter++)
{
       	cout << "Please enter a mark: ";
	cin >> mark;
	sum = sum + mark;
}
The following For loop also reads 10 marks and sums them up.
int sum = 0;
for (int counter = 10; counter > 0; counter--)
{
       	cout << "Please enter a mark: ";
	cin >> mark;
	sum = sum + mark;
}
Of course, all the For loops can be written as count-controlled While loops. For example, we can change the previous program segment to the following equivalent piece of code.
int sum = 0;
int counter = 1; 
while(counter <= 10)
{
       	cout << "Please enter a mark: ";
	cin >> mark;
	sum = sum + mark;
	counter++;
}



Copyright: Department of Computer Science, University of Regina.