Loops are essential in programming, and the for loop in C++ is one of the most versatile tools for iterating over sequences or performing repetitive tasks. In this tutorial, we’ll start with the syntax of the for loop and explore three examples, progressing from basic to more advanced scenarios.
1. For Loop Syntax
A for loop in C++ consists of three components:
for (initialization; condition; increment/decrement) {
// Code block to execute
}
- Initialization: Sets the starting point for the loop (e.g., int i = 0).
- Condition: The loop continues as long as this evaluates to true.
- Increment/Decrement: Updates the loop variable at each iteration.
2. Example 1: Basic Loop
This example demonstrates a simple loop that prints numbers from 1 to 5.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << "Number: " << i << endl;
}
return 0;
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
- int i = 1: Start from 1.
- i <= 5: Continue as long as i is less than or equal to 5.
- i++: Increment i by 1 at each iteration.
3. Example 2: Loop with Conditionals
This example adds a conditional statement inside the loop to print even numbers between 1 and 10.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
cout << "Even Number: " << i << endl;
}
}
return 0;
}
Output:
Even Number: 2
Even Number: 4
Even Number: 6
Even Number: 8
Even Number: 10
Explanation:
- The if (i % 2 == 0) condition checks if i is divisible by 2.
- Only even numbers are printed.
4. Example 3: Nested For Loops
In this example, we use nested loops to display a multiplication table from 1 to 5.
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
cout << i << " x " << j << " = " << i * j << "\t";
}
cout << endl; // New line after each row
}
return 0;
}
Output:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15
4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
Explanation:
- The outer loop (for i) iterates through rows.
- The inner loop (for j) handles each column in the row.
- i * j computes the product for the multiplication table.
'C++ Beginner' 카테고리의 다른 글
cpp_010: Arrays in C++ (0) | 2025.01.26 |
---|---|
cpp_009: While Loops and Break Statement in C++ (1) | 2025.01.15 |
cpp_007:Introduction to String Modifiers in C++ , Mastering String Manipulation (2) | 2025.01.06 |
cpp_006_Introduction to getline and cin.getline in C++: Handling User Input with Spaces (0) | 2025.01.05 |
cpp_005_Introduction to Strings (5) | 2025.01.01 |