In: Computer Science
C++ Code while loops. 1. Ask for file name and open file. 2. Do a priming read and make a while loop that A) Reads in numbers B) Sums them up. C) Counts how many there are. D) Prints "With 10 numbers, the average is blank.." every 10 numbers. So with every 10 numbers read in print the average. 3. After the loop calculate average of all numbers and print it. So for example once the file is open the code should print "With 10 numbers the average is ..." With 20 numbers the average is... " and so on.
#include<iostream>
#include<fstream>
using namespace std;
//driver function
int main(){
//variable to input file name
string name;
//prompt user to enter the file name
cout<<"Enter the name of the file to be opened: ";
cin>>name;
//create ifstream object
ifstream file;
//open file
file.open(name);
//num used to read in numbers from file
double num;
//sum stores total sum of all numbers
double sum=0;
//total stores count of numbers in file
int total=0;
//while EOF(end of file)
while(file>>num){
//increment count
total+=1;
//add to sum
sum+=num;
//if total number are multiple of 10 then print average
if(total%10==0){
double avg=sum/(double)total;
cout<<"With "<<total<<" numbers the average is
"<<avg<<"."<<endl;
}
}
//calculate the average of all the numbers
double avg=sum/(double)total;
//print the total sum , count and average of all the numbers.
cout<<"There are total "<<total<<" numbers in the
file and sum of all numbers is "<<sum<<" and their
average is "<<avg<<"."<<endl;
return 0;
}
Enter the name of the file to be opened: input.txt
With 10 numbers the average is 6.25.
With 20 numbers the average is 11.54.
There are total 22 numbers in the file and sum of all numbers is
246.1 and their average is 11.1864.
CODE
INPUT/OUTPUT
So if you still have any doubt regarding this solution please feel free to ask it in the comment section below and if it is helpful then please upvote this solution, THANK YOU.