Print Numbers from 1 to 100 Using a For Loop in C++
In this exercise, you will learn how to use a for loop in C++ to print numbers from 1 to 100. A for loop is commonly used when you know the number of iterations in advance. In this case, we want to iterate exactly 100 times, printing the numbers in sequence.
Iterative Logic
1. Initialization
The starting value of the counter. In this program, we initialize the variable to 1.
2. Condition
The loop will continue as long as the condition is true (counter reaches 100).
3. Increment
The counter will be increased after each iteration to progress through the range.
Key Concepts Learned:
- Control Flow: Mastering the
forloop for fixed iterations. - Sequential Output: Generating a numerical series in the console.
- Counter Management: Proper use of initialization and increment operators.
Course:
Control Flow & Logic
Objective
- 1. Use a
forloop to iterate from 1 to 100. - 2. In each iteration, print the current number.
- 3. Test the program to make sure it prints all numbers from 1 to 100.
Example C++ Exercise
main.cpp
For Loop
#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 1 to 100
for (int i = 1; i <= 100; ++i) {
cout << i << endl; // Print the current value of i
}
return 0; // Return 0 to indicate that the program executed successfully
}
Console Output:
1
2
3
...
99
100
Flow Control & Loops