Introduction to C++ | for Loop
C++ for Loop
The for loop in C++ is a control structure that allows you to repeat a block of code a certain number of times. It's commonly used when the number of iterations is known beforehand. It is very useful when you need to perform repetitive tasks such as iterating over arrays, ranges, or performing operations on numbers.
What is a for Loop?
The for loop consists of three parts:
- Initialization: It initializes the loop variable.
- Condition: It checks whether the loop should continue running.
- Increment/Decrement: It modifies the loop variable after each iteration.
Syntax:
Syntax of a for Loop
for (initialization; condition; increment/decrement) {
// code to be executed on each iteration
}
Example of for Loop
Here’s an example where a for
loop is used to print the numbers from 1 to 5:
Code Example
#include <iostream>
using namespace std;
int main() {
// for loop to print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
cout << "Number: " << i << endl;
}
return 0;
}
Output
Number: 2
Number: 3
Number: 4
Number: 5
Nested for Loops
In some cases, you might need to use multiple loops. A nested for loop is a loop inside another loop. This is useful for tasks such as iterating over multi-dimensional arrays or performing tasks with multiple variables.
Example of a nested for
loop:
Code Example: Nested for Loops
#include <iostream>
using namespace std;
int main() {
// Nested for loop to print a multiplication table
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
cout << i * j << "t"; // Multiplying i and j
}
cout << endl; // Move to the next line after each row
}
return 0;
}
Output
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Break and Continue in for Loop
You can also control the flow of a for loop using break
and continue
. The break
statement immediately exits the loop, while the continue
statement skips the current iteration and moves to the next one.
Example of using break
and continue
in a for loop:
Code Example with break and continue
#include <iostream>
using namespace std;
int main() {
// for loop with break and continue
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the iteration when i is 5
}
if (i == 8) {
break; // Exit the loop when i is 8
}
cout << "i = " << i << endl;
}
return 0;
}
Output
i = 2
i = 3
i = 4
i = 6
i = 7
Pro Tip:
💡 Pro Tip
For loops are particularly useful when the number of iterations is known in advance. When using nested loops, be careful about performance, as the time complexity increases exponentially with the number of nested loops. If performance is a concern, consider optimizing your algorithm or using other loop structures, such as while
loops or do-while
loops.