// File EOF Controlled while // Declare variables for integer read, sum of integ
ID: 3615417 • Letter: #
Question
// File EOF Controlled while
// Declare variables for integer read, sum of integers read, #of integers read
// Initialize sum and # to 0
// Declare input file stream
// Open input file "infile-5-B-2.txt"
// Read first number from file
// Execute the while loop until input stream reaches eof
// output integer read, add number tosum, increment #
// read next number from file
// Output sum and # and average
// Close input file
//
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int num, sum = 0, i = 0;
ifstream infile;
infile.open ("infile-5-B-2.txt");
cout << "Reading data from file"infile-5-B-2.txt"" << endl << endl;
if (infile)
while(!infile.eof())
{
infile >> num;
cout << num << " ";
sum = sum + num;
i++;
}
cout << endl << "Sum ofintegers " << sum << endl;
cout << "Number of integers " << i << endl ;
if (i != 0)
cout <<"Average of integers " << sum / i << endl ;
cout << endl ;
infile.close();
system("PAUSE");
return 0;
}
Explanation / Answer
please rate - thanks very minor change, corrected it in red, also fixed averagecalculation, you don't want it to be done as integer arithmetic // File EOF Controlled while // Declare variables for integer read, sum of integers read, # ofintegers read // Initialize sum and # to 0 // Declare input file stream // Open input file "infile-5-B-2.txt" // Read first number from file // Execute the while loop until input stream reaches eof // output integer read, add number to sum,increment # // read next number from file // Output sum and # and average // Close input file // #include #include using namespace std; int main() { int num, sum = 0, i = 0; ifstream infile; infile.open ("infile-5-B-2.txt"); coutRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.