C++ create a data file containg around(but not exactly) 100 integers.The numbers
ID: 3767783 • Letter: C
Question
C++
create a data file containg around(but not exactly) 100 integers.The numbers should be on multiple lines in the file, but do not include the same number of integers on each line of the file. write a c++ program to read the integers into an array with a max size of 200(i.e., search for eof marker.) The program should then determine and display(on the computer screen) the average value of the numbers(a real value), the number of integers greater than the average, and the number of integers less the average.
Explanation / Answer
Here is the logic for you. If you have any further queries, just get back to me.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
double calcAverage(int numbers[], int count)
{
double sum = 0;
for(int i = 0; i < count; i++) //For every number.
sum += numbers[i]; //Add it to sum.
return sum / count; //Return sum/count.
}
void numbersAboveAverage(int numbers[], int count, double average)
{
int newLine = 0;
for(int i = 0; i < count; i++) //For every number.
{
if(numbers[i] > average) //If it is above average.
{
cout<<setw(4)<<numbers[i]; //Print it.
newLine++; //Increment the numbers in a line.
if(newLine == 10) //If 10 numbers are printed consecutively.
{
cout<<endl; //Move to new line.
newLine = 0; //Reset the counter.
}
}
}
cout<<endl;
}
void numbersBelowAverage(int numbers[], int count, double average)
{
int newLine = 0;
for(int i = 0; i < count; i++) //For every number.
{
if(numbers[i] < average) //If it is below average.
{
cout<<setw(4)<<numbers[i]; //Print it.
newLine++; //Increment the numbers in a line.
if(newLine == 10) //If 10 numbers are printed consecutively.
{
cout<<endl; //Move to new line.
newLine = 0; //Reset the counter.
}
}
}
cout<<endl;
}
int main()
{
string fileName;
int numbers[200]; //Declare an array of size 200.
int count = 0;
cout<<"Enter the name of the file: "; //Read the name of the file that has integers.
cin>>fileName;
ifstream file; //Open that file.
file.open(fileName);
while(!file.eof()) //As long the eof is not reached.
file>>numbers[count++]; //Read each number into the array, and increment the counter.
double average = calcAverage(numbers, count); //Calculate average.
cout<<"Average of the numbers in the file is: "<<average<<endl; //Print average.
cout<<"Numbers above the average are: "<<endl;
numbersAboveAverage(numbers, count, average); //Print numbers above average.
cout<<"Numbers below the average are: "<<endl;
numbersBelowAverage(numbers, count, average); //Print numbers below average.
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.