C++: The for loop

This entry is part 15 of 61 in the series C++

The for loop allows one to execute a set of the instructions until a condition is met.

It has the following syntax:

for (initialization; test-condition; increment/decrement)
{
    Statement;
}

The test condition is similar to the test condition that we use in an if statement.

Consider the following example where we will perform an operation similar to below.

1+2+3+4+5+6+7+8+9+10=55

#include <iostream>
using namespace std;

int main()
{
	int sum = 0;

	for (int i = 1; i <= 10; ++i)
		sum += i;

	cout << "Sum of 1 to 10 inclusive is " << sum << endl;

	return 0;

}

The initialization is done within the for statement setting i = 1.  On each loop, a sequence of number will be added to the variable sum.

Notice we have been able to define i within the for loop itself.

forloop

 

 

Series Navigation<< C++: Logical operators
C++: Function >>