C++ loop Statement
C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop became false.
There are three types of loops in C++ programming language:
- for loop
- while loop
- do...while loop
C++ for Loop Statement
The
for loop is an iterative control statement. It executes loop's statement(s) several times until the condition of
for loop become false.
Syntax
for(initialize expr; condition expr; update expr ){
statement(s);
}
Working Process of for loop
- The initialize expression statement is executed only once and initialize variable expr.
- Then condition expression checks the condition applied, if it satisfies (true), statement(s) inside for loop executes otherwise execution exit from for loop.
- After statement(s) execution within for loop block, it update the variable expr and repeat step 2.
C++ for Loop Example
This example print counting from 1 to 10.
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 10; i++) {
cout<<i<<"\n";
}
return 0;
}
Output:
Infinite for Loop
Infinite for loop repeats the loop block infinite times. This happens when condition statement of for loop
always true (never false).
Infinite loop in
C++ programming language is terminated using shortcut keys
Ctrl + C.
Syntax
Infinite for loop Example
#include <iostream>
using namespace std;
int main()
{
int i=0;
for (; ; ) {
cout<<i++<<"\n";
}
return 0;
}
Output:
Print counting from 1 to infinite.