All lessons

4. Loops

for loops

0 of 5 activities0%

Reading 1

The counting pattern

Open

for (init; condition; step) { body } is built for counting.

A common form is for (int i = 0; i < n; i++) which runs the body n times with i = 0, 1, ..., n-1.

You can count upward or downward. Keep the three pieces clear: start, stop rule, and how i changes.

for (int i = 0; i < 5; i++) {
    cout << i << endl;
}

for (int i = 5; i >= 1; i--) {
    cout << i << endl;
}

Check 2

How many times

Open

How many times does for (int i = 1; i <= 4; i++) run?

Fill in 3

Increment

Open

The expression that adds one to i is written

Try it 4

Evens

Open

This prints even numbers. Try changing the upper bound.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Sum 1 to n

Open

Read an integer n (n >= 1). Print the sum of integers from 1 through n.

main.cpp
Loading editor…