So we have to write a program dealing with if statements, functions, and loops.
We have an input file that consist of 100 numbers. We are to calculate the average of those numbers depending on what the user enters (1 through a hundred). ANY HELP IS GREATLY APPRECIATED.
Here is our algorithm:
Algorithm solution (in pseudocode):
1. Declare variable inFile to get the data from an input file
2. Declare variables grade, counter, and total that hold a whole numbers.
3. Declare and initialize to zero a variable named sum that hold a whole numbers.
4. Open file input9.txt
5. Check if the file was opened (if not opened, show an error message and stop the program).
6. Prompt the user to enter the number of grades to process.
7. Get the value from the keyboard and store it in total.
8. Check if the value entered is outside the range (1…100). If the value is outside the range, display an error message and stop the program.
9. Set counter to 1.
10. While (counter does not reach total)
11. Get the value from the file and store it in grade.
12. Accumulate its value in sum.
13. Increment the counter.
14. Print the "The average is ", followed by the value returned by the function average (sum,total).
15. Closes the file.
Function average( ) receives the values of sum and total, calculates the average, and rounds it to the nearest whole number (ones) before returning it. Use appropriate type casting to avoid loss of information when calculating the average
And this is what we have written so far:
#include <iostream>
#include <fstream>
using namespace std;
int average(int a, int b);
int main()
{
//Declare variable inFile to get the data from an input file
ifstream inFile;
//Declare variables grade, counter, and total that hold a whole numbers.
int grade, counter, total;
//Declare and initialize to zero a variable named sum that hold a whole numbers.
int sum = 0;
//Open file input9.txt
inFile.open ("input9.txt");
//Check if the file was opened (if not opened, show an error message and stop the program).
if (!inFile)
{
cout << "File not found" << endl << endl;
return 1;
}
//Prompt the user to enter the number of grades to process.
cout << "How many grades (1 through 100) do you want to process? ";
//Get the value from the keyboard and store it in total.
cin >> total;
cout << endl;
//Check if the value entered is outside the range (1…100).
//If the value is outside the range, display an error message and stop the program.
if (total < 1 || total > 100)
{
cout << "Incorrect value, program terminated!" << endl << endl;
return 1;
}
//Set counter to 1.
counter = 1;
//While (counter does not reach total)
while (counter != total)
{
//Get the value from the file and store it in grade.
inFile >> grade;
//Accumulate its value in sum.
sum += grade;
//Increment the counter.
counter++;
}
//Print the "The average is ", followed by the value returned by the function average (sum,total).
cout << "The average is " << average(sum,total) << endl << endl;