C++ for Loop Examples

πŸ” C++ for Loop Examples

Below are clear and practical examples of the C++ for loop, from basic to advanced.


1. Print Numbers from 1 to 5

for (int i = 1; i <= 5; i++) {
cout << i << " ";
}

Output:

1 2 3 4 5

2. Print Even Numbers (1 to 10)

for (int i = 2; i <= 10; i += 2) {
cout << i << " ";
}

Output:

2 4 6 8 10

3. Print Numbers in Reverse Order

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

Output:

5 4 3 2 1

4. Sum of Numbers from 1 to 10

int sum = 0;

for (int i = 1; i <= 10; i++) {
sum += i;
}

cout << sum;

Output:

55

5. Multiplication Table of a Number

int n = 5;

for (int i = 1; i <= 10; i++) {
cout << n << ” x “ << i << ” = “ << n * i << endl;
}


6. Loop Through an Array

int arr[] = {10, 20, 30, 40};

for (int i = 0; i < 4; i++) {
cout << arr[i] << ” “;
}


7. Range-Based for Loop (Modern C++)

int arr[] = {5, 10, 15};

for (int x : arr) {
cout << x << ” “;
}

Output:

5 10 15

8. Nested for Loop Example

for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << i << j << " ";
}
cout << endl;
}

Output:

11 12 13
21 22 23
31 32 33

9. Print Characters of a String

string text = "C++";

for (int i = 0; i < text.length(); i++) {
cout << text[i] << ” “;
}

Output:

C + +

10. for Loop Without Initialization Inside

int i = 1;

for (; i <= 5; i++) {
cout << i << ” “;
}


Common Mistake ❌

for (int i = 1; i <= 5; i++); // extra semicolon
{
cout << i;
}

βœ” Correct:

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

Key Points

  • Use for loop when the number of iterations is known

  • Initialization, condition, and update are in one line

  • Supports nested loops and range-based loops

  • Clean and efficient for counting-based tasks

You may also like...