C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
printf("%.2f times %.2f equals %.2f\n\n",
num1, num2, result);
printf("Do you want to enter another pair of numbers ");
printf("to multiply (Y/N): ");
scanf(" %c", &choice);
// If the user enters a lowercase n, this if statement will
// convert it to an N
if (choice == 'n')
{
choice = 'N';
}
} while (choice != 'N');
return 0;
}

Although this program is simple and straightforward, it demonstrates an effective use of a
do...while loop. Again, you use the do...while construct instead of while when you want
to ensure that the code within the loop executes at least once. So after getting two floating-point
numbers from the user and displaying the result, the program asks the user if he or she wants to
multiply two new numbers. If the user enters Y (or any character other than N), the loop begins again
from the beginning.


Without the if statement in the loop, a lowercase n would not terminate the loop, but it seems
obvious that a user who enters n is looking to terminate the loop and just forgot to use the Shift key.
As mentioned earlier in the book, when programming, you cannot always count on the user entering
what you want, so when you can, you should anticipate common data-entry errors and provide
workarounds. Converting a lowercase n to N is not the only way you could account for this
possibility. You could also use a logical AND operator in the while portion of the loop, as follows:


Click here to view code image


} while (choice != 'N'&& choice != 'n');

In plain language, this is telling the program to keep running as long as the choice is not an
uppercase N or a lowercase n.


Tip

Chapter 19, “Getting More from Your Strings,” explains a simpler method to test for an
uppercase Y or N or a lowercase y or n with a built-in function named toupper().

The Absolute Minimum
The goal of this chapter was to show you how to repeat sections of code. The while
and do...while loops both repeat statements within their statement bodies. The
difference between the two statements lies in the placement of the relational test that
Free download pdf