Loops in C++
In programming, iteration statements (commonly known as loops) are used to execute a block of code repeatedly until a specific condition is met.
Using loops eliminates the need to write redundant code, reduces system memory footprint, and allows applications to process dynamic sequences or collections of data effectively.
Video Explanation

1. The for Loop
The for loop is an entry-controlled loop structure. It is ideal when you know the exact number of times you need to iterate before entering the loop block.
Syntax
ForLoopSyntax.cpp
for (initialization; condition; update) {
// Code block to be executed repeatedly
}
Example
ForLoopExample.cpp
#include <iostream>
int main() {
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration: " << i << "\n";
}
return 0;
}
Execution Mechanics:
- Initialization: Executes exactly once when entering the loop. Usually sets a counter variable (e.g.,
int i = 0). - Condition: Evaluated before every iteration. If
true, the loop body runs. Iffalse, execution exits the loop. - Update: Executes at the absolute end of each iteration cycle (e.g.,
++i), adjusting the counter variable before testing the condition again.
2. The Modern Range-Based for Loop
Introduced in modern C++ (C++11 and later), this syntax provides a cleaner, safer way to iterate through entire arrays or standard collections without tracking index counters manually.
Syntax
RangeBasedForLoopSyntax.cpp
for (element_type variable : collection) {
// Code block to execute for each element
}
Example
RangeBasedForLoopExample.cpp
#include <iostream>
int main() {
int binarySequence[] = {1, 2, 4, 8, 16};
for (int value : binarySequence) {
std::cout << "Value: " << value << "\n";
}
return 0;
}