Sample RunSolutioninclude include include using namespace st
Sample Run:
Solution
#include <bits/stdc++.h>
#include <fstream>
#include <cstdlib>
using namespace std;
// ** TODO **
// Create prototypes for the four functions described at the end of this lab.
void checkFile(const char* fname);
void fillArray(int* arr,int SIZE)
{
for(int i=0;i<SIZE;i++)
{
arr[i]=rand()%100+1;
}
}
void displayArray(int *arr,int SIZE)
{
for(int i=0;i<SIZE;i++)
{
cout<<arr[i]<<\" \";
}
}
int sumArray(int *arr,int SIZE)
{
int sum=0;
for(int i=0;i<SIZE;i++)
{
sum+=arr[i];
}
return sum;
}
void writeArray(ofstream& o,int* arr)
{
for(int i=0;i<25;i++)
{
o<<arr[i]<<\"\ \";
}
}
int main(int argc, char* argv[]) {
const int SIZE = 25;
// ** TODO **:
// Dynamically create an array of ints named array with SIZE elements.
int* arr=new int[SIZE];
// ** TODO **:
// Call fillArray to fill the array with random ints from 1 - 100
fillArray(arr,SIZE);
// ** TODO **:
// Call displayArray to print the elements on the screen.
displayArray(arr,SIZE);
// ** TODO **:
// Call sumArray to sum up the elements of the array.
int sum=sumArray(arr,SIZE);
// ** TODO **
// Display the sum of the array elements.
cout<<\"\ Sum is \"<<sum<<endl;
// ** TODO **:
// Open a file for output. The file name is nums.txt
// Call writeArray to store the elements in that file.
// Close that file.
ofstream file(\"nums.txt\");
writeArray(file,arr);
file.close();
// ** TODO **
// Release the memory you allocated for the array.
delete []arr;
checkFile(\"nums.txt\");
return 0;
}
void checkFile(const char* filename) {
int numRecs = 0;
int sum = 0;
int num;
ifstream infile(filename);
if (!infile) {
cout << \"Error reading file\" << endl;
} else {
infile >> num;
while (!infile.eof()) {
sum += num;
numRecs++;
infile >> num;
}
}
infile.close();
cout << \"Records in file: \" << numRecs << endl;
cout << \"Sum of records in file: \" << sum << endl;
}
=======================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ sortnumfile.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
84 87 78 16 94 36 87 93 50 22 63 28 91 60 64 27 41 27 73 37 12 69 68 30 83
Sum is 1420
Records in file: 25
Sum of records in file: 1420

