Loops are used to execute a block of code for a specified number of times. ‘while’ loop is used to execute a block of code till certain condition is true. The loop is not executed if the condition becomes false. The following program shows a ‘while’ loop to print ‘Hello world’ five times.
#include <iostream>
using namespace std;
int main () {
int n = 1;
while (n <= 5) {
cout<<"Hello world!"<<endl;
n++;
}
return 0;
}
The ‘do-while’ loop executes the block of code once before the condition is checked. The body of the code to be executed is in ‘do’ statement and specific condition for the execution is in the while statement. The following code shows a ‘do-while’ loop which prints ‘Hello world’ five times.
#include<iostream>
using namespace std;
int main () {
int n = 1;
do {
cout<<"Hello world!"<<endl;
n++;
}
while (n<=5);
return 0;
}