For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations are known in advance.
for(Initialization; Condition; Increment/decrement){
//code
} #include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; i++) {
cout << i << endl;
}
}Check Result here
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations is not known in advance.
while(condition){
//code
} #include <iostream>
using namespace std;
int main()
{
int i=1;
while ( i <= 5) {
cout << i << endl;
i++;
}
}Check result here
Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.
do{
//code
} while(condition); #include <iostream>
using namespace std;
int main()
{
int i=1;
do {
cout << i << endl;
i++;
} while (i<=5);
}