Do While Loop in C++ Programming
The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.The do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.
- The first body of the loop is executed.
- The condition check to true, the body of the loop inside the do statement is executed again.
- The condition is check again.
- This process continues until the condition is false.
- When the condition to false, the loop stops.
Syntax:
do
{
// body of loop;
// Increment (or) Decrement;
} while(Condition) ;
The program is an implementation of the do-while loop in C++.
- The program starts by declaring two integer variables: n and i. The variable i is initialized to 1. The user is prompted to enter the value of n. The value entered by the user is read and stored in the variable n using the cin statement.
- A do-while loop is used to print the even numbers between 1 and n. The loop body starts with an if statement that checks if the current value of i is even (i.e., divisible by 2 using the modulo operator %). If i is even, then its value is printed using the cout statement.
- In every iteration, the value of i is incremented by 1 using the i++ statement.
- The loop continues as long as the value of i is less than or equal to n.
- Once the loop condition becomes false, i.e., i becomes greater than n, the loop exits and the program terminates.
Source Code
//Do While
#include<iostream>
using namespace std;
int main()
{
int n,i=1;
cout<<"\nEnter The Limit : ";
cin>>n;
do
{
if(i%2==0)
cout<<i<<endl;
i++;
}while(i<=n);
return 0;
}
Output
Enter The Limit : 20
2
4
6
8
10
12
14
16
18
20
To download raw file
Click Here