For loops are a fundamental concept in programming that allows you to execute a block of code multiple times. They are particularly useful when you know in advance how many times you want to repeat a set of instructions. Let’s break down the structure of a for loop:
for (initialization; condition; increment) {
// Code to be executed
}
Let’s look at a simple example where we print numbers from 1 to 5.
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
std::cout << i << std::endl;
}
return 0;
}
i
to 1.i
is less than or equal to 5.i
by 1.1
2
3
4
5
In this example, we’ll use a for loop to iterate through an array of numbers and print each one.
#include <iostream>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int length = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < length; i++) {
std::cout << numbers[i] << std::endl;
}
return 0;
}
numbers
containing five integers.10
20
30
40
50
Nested for loops are useful when working with multi-dimensional data. Here’s how to create a simple multiplication table.
```cpp
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
std::cout << i * j <<