Start learning free

LESSON 151 OF 667 · WHILE LOOPS & FOR LOOPS

Looping In Reverse in C++

Lesson

A for loop can also count backwards, as long as we define the right conditions. For example:

for (int i = 7; i > 2; i--) {
	cout << i << endl;
}

The output of this code is:

7
6
5
4
3

Let's break down this code:

  • The initialization statement is int i = 7, so we start iterating from number 7.

  • We loop as long as i > 2, so we'll end at number 3. We could've written i >= 3 and it would still be correct.

  • The iteration statement is i--, so we decrease our number by 1 every time.


Assignment

Let's print all numbers from 5 through -5 in decreasing order.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check