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)

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.


#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.




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

Leave a comment

Leave a Reply