Hi there, we’re Harisystems
"Unlock your potential and soar to new heights with our exclusive online courses! Ignite your passion, acquire valuable skills, and embrace limitless possibilities. Don't miss out on our limited-time sale - invest in yourself today and embark on a journey of personal and professional growth. Enroll now and shape your future with knowledge that lasts a lifetime!".
For corporate trainings, projects, and real world experience reach us. We believe that education should be accessible to all, regardless of geographical location or background.
1C++ For Loop
In C++, the for loop provides a concise and efficient way to iterate over a block of code for a specific number of times. It allows you to control the flow of your program based on a counter variable. In this article, we will explore the usage of the for loop in C++ with examples.
1. Basic For Loop
The basic syntax of a for loop consists of three parts: initialization, condition, and increment/decrement. The code block within the for loop is executed repeatedly as long as the condition evaluates to true. Here's an example:
#include <iostream>
int main() {
for (int i = 0; i < 5; i++) {
std::cout << "Count: " << i << std::endl;
}
return 0;
}
In the above code, the for loop initializes the variable i
to 0, executes the code block as long as i
is less than 5, and increments i
by 1 after each iteration. The count value is displayed on the console.
2. Nested For Loop
You can nest one for loop inside another to create complex loop structures. This is useful when dealing with multi-dimensional data or performing matrix operations. Here's an example:
#include <iostream>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
std::cout << "(" << i << ", " << j << ")" << std::endl;
}
}
return 0;
}
In the above code, the outer for loop controls the variable i
from 1 to 3, and the inner for loop controls the variable j
from 1 to 3. The program displays the combination of i
and j
in a matrix-like format.
3. For Loop with Arrays
The for loop is commonly used with arrays to iterate over the elements of the array. Here's an example:
#include <iostream>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
std::cout << "Number: " << numbers[i] << std::endl;
}
return 0;
}
In the above code, the for loop iterates over the elements of the array numbers
and displays each element on the console.
The for loop is a versatile construct in C++ that allows you to iterate over a block of code for a specified number of times. It provides a compact and readable way to perform repetitive tasks, iterate over arrays, and create nested loop structures. Use the for loop to control the flow of your program efficiently and simplify complex iteration tasks.