Repetitive Statements For Loop - Abdul Rehman
Repetitive Statements For Loop - Abdul Rehman
For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100
times, we can use a loop.
That was just a simple example; we can achieve much more efficiency and sophistication in our programs by
making effective use of loops.
for loop
while loop
do...while loop
This tutorial focuses on C++ for loop. We will learn about the other type of loops in the upcoming tutorials.
Here,
update - updates the value of initialized variables and again checks the condition
To learn more about conditions , check out our tutorial on C++ Relational and Logical Operators (/cpp-
programming/relational-logical-operators).
Flowchart of for Loop in C++
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Output
1 2 3 4 5
#include <iostream>
int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Here is how this program works
#include <iostream>
int main() {
int num, sum;
sum = 0;
return 0;
}
Output
Here,
i <= num : runs the loop as long as i is less than or equal to num
When i becomes 11 , the condition is false and sum will be equal to 0 + 1 + 2 + ... + 10 .
Here, for every value in the collection , the for loop is executed and the value is assigned to the variable .
Example 4: Range Based for Loop
#include <iostream>
int main() {
return 0;
}
Output
1 2 3 4 5 6 7 8 9 10
In the above program, we have declared and initialized an int array named num_array . It has 10 items.
Here, we have used a range-based for loop to access all the items in the array.
If the condition in a for loop is always true , it runs forever (until memory is full). For example,
// infinite for loop
for(int i = 1; i > 0; i++) {
// block of code
}
In the above program, the condition is always true which will then run the code for infinite times.