🔄 Do While Loop in C++
The do while
loop is similar to a while
loop, but it executes the code block at least once, even if the condition is false.
🔹 Syntax
do {
// Code to execute
} while (condition);
- The code executes first and then checks the condition.
- If the condition is
true
, the loop repeats.
1️⃣ Printing Array using Do While Loop
📌 Print all elements of an array using a do while
loop.
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int i = 0;
do {
cout << arr[i] << " ";
i++;
} while (i < size);
return 0;
}
🔹 Output
10 20 30 40 50
2️⃣ Printing a Given Word using Do While Loop
📌 Print a word multiple times using a do while
loop.
#include <iostream>
using namespace std;
int main() {
string word;
int times, i = 1;
cout << "Enter a word: ";
cin >> word;
cout << "How many times to print? ";
cin >> times;
do {
cout << word << endl;
i++;
} while (i <= times);
return 0;
}
🔹 Output
Enter a word: Hello
How many times to print? 3
Hello
Hello
Hello
3️⃣ Printing Numbers using Do While Loop
📌 Print numbers from 1
to N
using a do while
loop.
#include <iostream>
using namespace std;
int main() {
int n, i = 1;
cout << "Enter a number: ";
cin >> n;
do {
cout << i << " ";
i++;
} while (i <= n);
return 0;
}
🔹 Output
Enter a number: 5
1 2 3 4 5
📌 Summary
✔ do while
executes at least once, even if the condition is false.
✔ It’s useful when user input is needed before checking conditions.
✔ while
checks before execution, whereas do while
checks after execution.
Would you like more examples or real-world applications? 🚀
0 Comments