Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Write a program in C ++ that outputs 500 single digit integers to a file name

ID: 3535927 • Letter: 1

Question

1. Write a program in C ++ that outputs 500 single digit integers to a file named "integerfile.txt", each integer is separated by a newline character.

2. Write a program that reads from the file created by question 1.

a. Print out the contents of the file. (50 integers per line)

b. Calculate the sum of the integers and print out the sum.

c. Count the number of times each digit appears and output the counts. (Use 1-D array to store the counts) .

please post the correct answer. do not submit the wrong answer.

Explanation / Answer

1)

#include <iostream>

#include <fstream>


using namespace std;


int main(){

int i;

ofstream myfile;

myfile.open("integerfile.txt");

for( i=0; i<500; i++){

myfile<< (rand()) ;

}

myfile.close();

return 0;

}


2)

#include <iostream>

#include <fstream>


using namespace std;


int main(){

int i,j=0;

int array[500];

ifstream myfile;

// reading from file

myfile.open("integerfile.txt");

for( i=0; i<500; i++){

myfile>>array[i] ;

}

myfile.close();

// printing the conternts of file

for( i=0; i<500; i++){

cout<<array[i]<<" ";

j++;

if ( j== 50){

j =0;

cout<<endl;

}

}

// calculating the sum

int sum =0;

for(i=0; i<500; i++){

sum = sum+array[i];

}

cout<<"The sum is"<<sum;

// count the numbers of each times each digit is occurrred

int count[10];

for(i=0; i<500; i++){

switch( array[i] ){

case 0: count[0]++;

break;

case 1: count[1]++;

break;

case 2: count[2]++;

break;

case 3: count[3]++;

break;

case 4: count[4]++;

break;

case 5: count[5]++;

break;

case 6: count[6]++;

break;

case 7: count[7]++;

break;

case 8: count[8]++;

break;

case 9: count[9]++;

break;

default:

break;

}

}

for( i=0; i<10; i++){

count<<i<<"-"<<count[i];

}

return 0;

}