3.3. For Loops

Even though the while type of construct is very useful in a wide variety of situations, another iterative structure, the for statement, can be used to iterate across a range of values easily. However, you must first find the length of your container. For vectors, you can simply call the .length() function. For arrays, the number of elements can be found by getting the size in memory of the array by using the sizeof() function, and then dividing it by the size of the first element of the array using the same sizeof() function. Because all elements in C++ arrays are the same type, they take the same amount of space and that can be used to find the number of elements the Array contains!

An optional secondary version of the for loop has been commented out of the above code. You can try running this in your version of C++ to see if it works, but in some older versions of C++, such as C++98, it does not.

The above loop assigns the variable index to be each successive value from 0 to numsSize.

Then, the value at that index in the array is printed to the console.

A common use of the for statement is to implement definite iteration over a range of values. The code

will use cout five times. The value of the variable i will start at 0 and go through the full sequence of values 0,1,2,3,4. This valu e is then squared and printed.

The other very useful version of this iteration structure is used to process each character of a string. The following code fragment iterates over a list of strings and for each string processes each character by appending it to a list. The result is a list of all the letters in all of the words.

3.4. Check yourself

#include <iostream>
using namespace std;

int main() {

    for (int counter=0; counter<4; counter++) {
        cout << counter * 2 << endl;

    return 0;

    Q-1: Using the code above please select the answer that should appear?

  • 0, 2, 4, 6
  • Good Job!
  • 0, 0, 0, 0
  • Not quite, take another look at the operation happening in the cout line
  • Runtime error
  • Not quite, take another look at the for loop
  • 0, 1, 2, 3
  • Not quite, take another look at the operation happening in the cout line
You have attempted of activities on this page
Next Section - 3.5. Summary