other loops is that in the do-while loop the condition comes after the statement(s). It takes the following form:
do
{
statement(s);
}while (condition);
This means that the statement(s) inside the loop will be executed at least once regardless of the condition being evaluated. Consider the following example:
/* Program-5.5 */
#include <stdio.h>
int main()
{
float price, total;
total = 0 ; //set initial value to 0
do //request for price
{
printf("Enter price (0 to end): ");
scanf("%f", &price); //get price
total += price;
} while (price > 0); // if valid price continue loop
printf("Total : %.2f", total);
return 0;
}
Execution of Program-5.5 with some inputs will display the following:
Enter price (0 to end): 10
Enter price (0 to end): 12.50
Enter price (0 to end): 99.99
Enter price (0 to end): 0
Total : 122.49
Program-5.5 accepts prices of items from the keyboard and then it computes the total. User can enter any number of prices and the program will add them up. It will terminate only if zero or any negative number is entered. In order to calculate the total or terminate the program there should be at least one input from the keyboard. Therefore in this type of a program do-while loop is recommended than the while loop.
No comments:
Post a Comment