Do-while Loop in C++
Do while loop
On this page we will discuss about do while loop in C++ . Do while is a looping structure in C++, these types of loops are called Exit control or Post-test loops . In a do-while first the loop body is executed and then the test condition is checked as a result one time execution of loop body is assured even if the condition is false for the first time
Do While Loop in C++ Language
- Do while loop is very similar to the while loop. To do repetitive work control structure has been created.
- In do while we execute some statements first and then check a condition.
- That is why Do-while is known as exit controlled loop. Which means that it will be implemented atleast once
- If the condition is met we execute it again. We keep doing this until the condition keeps meeting.
Syntax:
do{ // execute statement(s) }while(condition(s));
Along with increment and initialization logic it may look like :
initialization; do{ // execute statement(s) incrementation; }while(condition(s));
Example 1:
Run
#include<iostream> using namespace std; int main() { int i = 1000; // i is set as 1000 which is definitely greater than 5 // the condition set below is (i <= 5) which will surely be never met // as the loop is incrementing (i++) // but still the loop is executed once anyways do{ cout << i << ". Hello World\n"; i++; } while(i <= 5); return 0; }
Output:
1000. Hello World
Example 2:
#include using namespace std; int main() { int n = 25; int i = 1; do{ cout << i << " "; i++; } while(i <= n); return 0; }
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Example 3:
Run
#include<iostream> using namespace std; int main() { int n = 100; int i = 1; do{ // if divisible by 7 must leave 0 remainder // on applying modulo operator if(i % 7 == 0){ cout << i << " "; } i++; } while(i <= n); return 0; }
Output:
7 14 21 28 35 42 49 56 63 70 77 84 91 98
Example 4:
#include using namespace std; int main() { char i='A';//inialisation do { cout << i << " : " << (int) i << " "; i++; // ascii codes are incremented } while(i<='Z'); // internally ascicodes are compared return 0; }
Output:
A : 65 B : 66 C : 67 D : 68 E : 69 F : 70 G : 71 H : 72 I : 73 J : 74 K : 75 L : 76 M : 77 N : 78 O : 79 P : 80 Q : 81 R : 82 S : 83 T : 84 U : 85 V : 86 W : 87 X : 88 Y : 89 Z : 90
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment