Introduction to do-while
Loop in C++
Loops are used in C++ to repeatedly run a block of code if an initial requirement is satisfied. The C++ do-while Loop Examples is distinct from the other loop types in C++ because it ensures that the code inside the loop will be executed at least once, regardless of the situation. Other loop types include for, while, and others.
Syntax of do-while
Loop
Before diving into examples, let’s first understand the syntax of a do-while
loop:
do {
// Statements to be executed
} while (condition);
How It Works
- Initialization: The loop starts with executing the code block within the
do
statement. - Condition Check: After the code block has been executed once, the condition specified in the
while
statement is evaluated. - Repeat or Exit: If the condition is
true
, the loop repeats. If it isfalse
, the loop terminates, and the program continues with the next statement after the loop.
The key difference between a while
loop and a do-while
loop is that the while
loop checks the condition before executing the code block, whereas the do-while
loop checks the condition after the code block has been executed.
Example 1: Simple do-while
Loop
Let’s start with a basic example to illustrate how a C++ do-while Loop Examples works.
Example: Print Numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
do {
cout << i << " ";
i++;
} while (i <= 5);
return 0;
}
Explanation
- Initialization: The integer
i
is initialized to1
. - Execution: The code inside the
do
block prints the value ofi
, and theni
is incremented by1
. - Condition Check: After printing the first value (which is
1
), the condition(i <= 5)
is checked. If it istrue
, the loop continues. - Output: The output of this code will be
1 2 3 4 5
.
This example demonstrates how the do-while
loop ensures that the code block is executed at least once.
Example 2: do-while
Loop with User Input
A common use case for the do-while
loop is to repeatedly ask the user for input until a valid input is provided.
Example: Validating User Input
#include <iostream>
using namespace std;
int main() {
int number;
do {
cout << "Enter a number between 1 and 10: ";
cin >> number;
} while (number < 1 || number > 10);
cout << "You entered: " << number << endl;
return 0;
}
Explanation
- User Input: The application asks the user to input a number in the range of 1 and 10.
- Validation: The while loop determines if the input is legitimate (that is, falls between 1 and 10). The loop continues and the user is prompted once more if the input is deemed invalid.
- Output: The software shows the entered number after the loop breaks when a valid input is received.
.
This example shows how the do-while
loop can be effectively used to ensure the user enters valid data.
Example 3: do-while
Loop with Sentinel Value
Another practical application of the do-while
loop is in scenarios where the loop continues until a sentinel value is entered.
Example: Summing Numbers Until Zero is Entered
#include <iostream>
using namespace std;
int main() {
int number, sum = 0;
do {
cout << "Enter a number (0 to stop): ";
cin >> number;
sum += number;
} while (number != 0);
cout << "The total sum is: " << sum << endl;
return 0;
}
Explanation
- Sentinel Value: As long as the user enters numbers, the loop adds them to the total. When the user inputs 0, the loop ends.
- Output: After removing the sentinel value 0, the software reports the total sum of all the numbers entered.
- This example shows how data can be processed using a do-while loop until a particular value (sentinel value) is reached.
Example 4: Nested do-while
Loops
Nested loops are loops within loops. The do-while
loop can also be nested inside another do-while
loop or any other type of loop.
Example: Multiplication Table
#include <iostream>
using namespace std;
int main() {
int i = 1, j;
do {
j = 1;
do {
cout << i << " * " << j << " = " << i * j << "\t";
j++;
} while (j <= 10);
cout << endl;
i++;
} while (i <= 10);
return 0;
}
Explanation
- Outer Loop: The outer
do-while
loop iterates over the rows, representing the numbers from 1 to 10. - Inner Loop: The inner
do-while
loop iterates over the columns, representing the multiplier from 1 to 10 for each row. - Output: The program prints a multiplication table from 1×1 to 10×10.
This example demonstrates how nested do-while
loops can be used to generate complex patterns like multiplication tables.
Example 5: Using do-while
Loop for Menu-Driven Programs
Menu-driven programs often use do-while
loops to repeatedly display the menu until the user decides to exit.
Example: Simple Calculator
#include <iostream>
using namespace std;
int main() {
int choice;
double num1, num2;
do {
cout << "Simple Calculator\n";
cout << "1. Add\n";
cout << "2. Subtract\n";
cout << "3. Multiply\n";
cout << "4. Divide\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
if (choice >= 1 && choice <= 4) {
cout << "Enter two numbers: ";
cin >> num1 >> num2;
}
switch (choice) {
case 1:
cout << "Result: " << num1 + num2 << endl;
break;
case 2:
cout << "Result: " << num1 - num2 << endl;
break;
case 3:
cout << "Result: " << num1 * num2 << endl;
break;
case 4:
if (num2 != 0)
cout << "Result: " << num1 / num2 << endl;
else
cout << "Cannot divide by zero" << endl;
break;
case 5:
cout << "Exiting the calculator." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != 5);
return 0;
}
Explanation
- Menu Display: The menu is displayed using a
do-while
loop. The loop continues until the user selects the option to exit (choice5
). - Switch Case: Based on the user’s choice, different operations (addition, subtraction, multiplication, division) are performed.
- Validation: The loop ensures that the program only exits when the user chooses to do so.
This example highlights the use of do-while
loops in creating user-friendly menu-driven programs.
Example 6: do-while
Loop with Arrays
The do-while
loop can also be used to iterate over arrays, processing each element until a specific condition is met.
Example: Finding the Maximum Element in an Array
#include <iostream>
using namespace std;
int main() {
int arr[] = {3, 5, 7, 2, 8, 1, 9, 4};
int max = arr[0];
int i = 1;
do {
if (arr[i] > max) {
max = arr[i];
}
i++;
} while (i < sizeof(arr) / sizeof(arr[0]));
cout << "The maximum element is: " << max << endl;
return 0;
}
Explanation
- Array Iteration: The
do-while
loop iterates through each element of the array. - Max Calculation: During each iteration, the current element is compared with the current maximum value. If it is greater, the maximum value is updated.
- Output: The program prints the maximum element in the array.
This example demonstrates how the do-while
loop can be used to process arrays in C++.
Example 7: Using do-while
Loop for String Manipulation
String manipulation is another area where the C++ do-while Loop Examples can be effectively used.
Example: Reversing a String
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[] = "Hello, World!";
int len = strlen(str);
char reversed[50];
int i = 0, j = len - 1;
do {
reversed[i] = str[j];
i++;
j--;
} while (j >= 0);
reversed[i] = '\0'; // Null-terminate the reversed string
cout << "Original String: " << str << endl;
cout << "Reversed String: " << reversed << endl;
return 0;
}
Explanation
- String Reversal: The
do-while
loop iterates over the original string from the end to the beginning, copying characters to the reversed string. - Output: The program outputs both the original and the reversed strings.
This example illustrates how the do-while
loop can be used for string manipulation tasks like reversing a string.
Conclusion
In C++, the do-while loop provides a versatile and efficient control structure. Because it ensures that the code block inside the US city is completed at least early, it is especially helpful in schemes where you want to ensure that the operation is completed before examining a condition. The do-while loop explains to be a vital form in a C++ do-while Loop Examples notably a hobbyist’s toolset from basic number publication and customer opinion confirmation to more difficult chores like menu-driven programs, array convert, and series direction.