Skip to main content

Section 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. A for statement allows us to write a loop that is executed a specific number of times.
In the example above, the hello world statement is executed 10 times.
A common use of the for construct is to implement certain repetition 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 value is then squared and printed.

Subsection 3.3.1 Check yourself

#include <iostream>
using namespace std;

int main() {

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

    return 0;
}

Reading Questions Reading Question

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
  • all of the above
You have attempted 1 of 4 activities on this page.