C++ For loop

This article covers the C++ for loop.

The C++ for loop is used to create a loop that runs a certain amount of times, until the given condition has been met. This is in contrast to it’s counter parts, the while loop and do while loop which iterate for an unspecified number of times as long as a condition is met.

For loops in C++ are more flexible and can be manipulated to a greater degree than for loops in languages like VB.NET or Python. If you’ve studied for loops in Java, learning the for loop in C++ will be a piece of cake, due to the massive similarities.

Make sure to use the correct loop for your program. Evaluate the pros and cons of each loop and be clear on what your program requires.


Syntax

Below is the general form of the for loop in C++.

for(initialization; condition; increment)
{
statement sequence
}
  • initialization: This is where the loop control variables gets declared and initialized. Typically all loop control variables are initialized from zero.
  • condition: The condition that must become false for the For Loop to end.
  • increment: Defines the increment of the loop control variables every iteration.

For Loop Example

This a C++ for loop in it’s most basic and most commonly used form. A simple initialization starting from 0, a given condition (less than 10), and an increment of 1 after each iteration of the loop.

#include <iostream>
using namespace std;

int main () {

   for( int i = 0; i < 10; i = i + 1 ) {
      cout << "value of i: " << i << endl;
   }

   return 0;
}
value of i: 0
value of i: 1
value of i: 2
value of i: 3
value of i: 4
value of i: 5
value of i: 6
value of i: 7
value of i: 8
value of i: 9

For Loop – Iteration version

For loops are meant for more than what was shown above. Another very popular use of the for loop, is for iterating over sequences of data, otherwise known as data collectors such as Arrays.

The code below will iterate over each element of the Array called my_array printing out each element individually. The value of each element is stored in the variable declared in the for loop. In this case, the value is stored in the variable "n". The value of "n" updates to a new element with every iteration.

#include <iostream>
using namespace std;

int main () {

   int my_array[] = {6, 9, 2, 5, 7, 1, 4, 0, 6, 3};

   for( int n : my_array ) {
      cout << "value of n is " << n << endl;
   }

   return 0;
}

Shown below is the output of the above code.

value of n is 6
value of n is 9
value of n is 2
value of n is 5
value of n is 7
value of n is 1
value of n is 4
value of n is 0
value of n is 6
value of n is 3

This marks the end of the C++ For Loops Article. Any suggestions for Coderslegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments