Question: Consider the following C++ program. It starts by prompting the user to enter an even positive number. Then it uses a do-while loop to check
Consider the following C++ program. It starts by prompting the user to enter an even positive number. Then it uses a do-while loop to check the users input until the desired number is entered.
#includeusing namespace std; int main() { int num = 0; do { cout << "Enter a positive even number: "; cin >> num; } while (num <= 0); cout << "num = " << num << endl; return 0; }
Step 1: Copy this program into your C++ program editor, and compile it. Hopefully you will not get any error messages.
Step 2: Run your program type in "-3" to see what happens. Now try "4". Try several other input values to see what happens. You should see that the program prompts you for values until a positive number is entered.
Step 3: Sadly, the code above is not checking for even numbers. As you know, the modulo operator % is used to give us the remainder after integer division. Hence, (num%2 == 0) will be true for even numbers, and (num%2 == 1) will be true for odd numbers. Edit your program and replace (num <= 0) with the logical expression for even numbers.
Step 4: Compile and run your program again, and type in an even number. Now type in an odd number. What happened? Your do-while loop is essentially saying "repeat looping while the number is even". This is the opposite of what we want. Edit your program and replace the condition with (num%2 == 1) and now your program should stop when an even number is entered.
Step 5: Run your program again and enter "-4". Your do-while loop should stop because this number is even, but we were actually wanting the user to enter a positive even number. Hence we want a do-while loop condition that is true if "number is not positive" (num <= 0) OR "number is odd" (num%2 == 1). If we use an AND here by mistake the do-while loop will not work correctly.
Step 6: Edit your program one last time and add the logical expression to make the do-while loop stop when the user types in a positive even number. Test with "-4" and variety of values to verify it is working as desired.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
