In: Computer Science
Exercise 3.4.1
In P3_4_1.cpp (BELOW), right at the beginning, the program initializes choice to 1. This forces the while loop to run at least once. If you use a do ... while instead, you wouldn't need to initialize the choice. Re-write the below program, call the new program ex341.cpp, so that is uses do ... while. Do not initialize the choice to 1 this time. Compile and run the program.
Answer questions:
Does the program work the same way? Write your answer as a comment inside the code of your ex341.cpp file.
// P3_4_1.cpp - Read and average some integers, print the result.
// This program continue asking for a new number until the user enters a 0 to terminate the program
#include <iostream> using namespace std;
int main(void)
{ int x;
int count = 0; // (1) initialize a counter to 0 to count number of values
int choice = 1; // This is the choice that controls the looping continuation or termination
double sum = 0; // initialize sum to 0 to make sure sum at the beginning is 0
double average;
while( choice == 1) // (2) read N grades and compute their sum, count ensures N entries
{
// read each number and compute the sum:
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; // (3) update the count
// prompt the user:
cout << "Do you wish to enter another grade? (1 for yes and 0 or other key for no): "
<< endl;
cin >> choice;
}
if(count == 0)
cout << "You haven't entered any number. No average will be computed. Bye!\n";
else{
average = sum/count; //Notice that we have divided by count this time
cout << "The average of these " << count << " grades is " << average <<"." << endl;
}
return 0;
}
Here is code:
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int choice;
int N; // Number of values for which the average must be
computed.
double sum = 0;
double average;
char repeat;
do
{
count = 0; // (1) initialize a counter to 0 to count number of
values
choice = 1; // This is the choice that controls the looping
continuation or termination
while (choice == 1) // (2) read N grades and compute their sum,
count ensures N entries
{
// read each number and compute the sum:
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; // (3) update the count
// prompt the user:
cout << "Do you wish to enter another grade? (1 for yes and 0
or other key for no): "
<< endl;
cin >> choice;
}
if (count == 0)
cout << "You haven't entered any number. No average will be
computed. Bye!\n";
else
{
average = sum / count; //Notice that we have divided by count this
time
cout << "The average of these " << count << "
grades is " << average << "." << endl;
}
// (4) read user input and wheather user wants to play again.
cout << "\nDo you want to run again (Y/N) : ";
cin >> repeat;
} while (repeat == 'Y');
return 0;
}
Output: