Print Numbers from 10 to 1 in Reverse Order in C++
In this exercise, you will write a C++ program that prints numbers from 10 to 1 in reverse order. This will help you practice using loops, particularly with decrementing values. By using a for loop or a while loop, you can iterate through a sequence in reverse.
Iterative Logic
1. Initialization
The loop starts with the control variable i set to 10, which is the beginning of our reverse sequence.
2. Condition
The loop continues to execute as long as i is greater than or equal to 1 ($i \geq 1$).
3. Decrement
In each step, we use the --i operator to reduce the value, moving backwards through the numbers.
Key Concepts Learned:
- Reverse Iteration: Learning how to count downwards in a loop.
- Decrement Operator: Using
--to decrease variable values. - Loop Control: Managing loop boundaries for decreasing sequences.
Objective
- 1. Use a loop to iterate from 10 to 1.
- 2. In each iteration, print the current number.
- 3. Test the program to ensure that the numbers are printed in reverse order from 10 down to 1.
Example C++ Exercise
#include <iostream> // Include the iostream library for input and output
using namespace std; // Use the standard namespace
// Main function - the entry point of the program
int main() {
// Use a for loop to iterate from 10 to 1
for (int i = 10; i >= 1; --i) {
cout << i << endl; // Print the current value of i (the number)
}
return 0; // Return 0 to indicate that the program executed successfully
}
Console Output:
10
9
8
7
6
5
4
3
2
1