‘for’ loop is used to repeat execution of a block of code for a specified number of times. ‘for’ loop contains three statements- initialization, condition and increment. The initialization statement runs for one time, conditional statement checks for condition if it is true or false. increment statement increases the value till condition is true.
The following program shows a ‘for’ loop for printing “Hello world!” four times.
#include<iostream>
using namespace std;
int main () {
for (int i=1 ; i<5 ; i++ ) {
cout<<"Hello world!"<<endl;
}
return 0;
}
The following program shows to print sum of numbers from 10 to 15 using the for loop.
#include<iostream>
using namespace std;
int main () {
int sum;
sum = 0;
for (int a = 10; a <= 15; a++ ) {
sum = sum + a;
}
cout<<"The sum of numbers from 10 to 15 is "<<sum;
return 0;
}