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

Create a C++ program to read in a le of pseudorandomly generated integers and di

ID: 3538160 • Letter: C

Question

Create a C++ program to read in a le of pseudorandomly generated integers and display a formatted table of how many times each digit occurs. Note, that zero cannot occur since we don't write numbers with a leading zero normally. Each line in the input le will contain one integer between 0 and 101. A sample le is on the class web site. Your program should

read the values and store the count of each digit in an array. You must create the following

functions:

int rstDigit(int integer);

// returns the rst digit (leftmost, most signicant) of an integer

void digitCount(int array[], int size, int digit);

// increments the count of digit in the array

void displayCount(int array[], int size);

// display the array data in a nicely formatted table (see below)

The program output should be a nicely formatted table showing the digit name, number of

times the digit occurred, and the percentage. A partial sample of the output is shown below.

Digit Count Percentage

-----------------------------------------------------------

One 17 4.0%

Two 22 6.5%

Explanation / Answer

//assumes input is in a file called "input.txt"

#include <iostream>

#include <fstream>

#include <string>

#include <cstdlib>

using namespace std;



int rstDigit(int integer)

{

return (integer%10);

}


// returns the rst digit (leftmost, most signicant) of an integer


void digitCount(int array[], int size, int digit)

{   

if(digit!=0)

array[digit-1]++;   

}


// increments the count of digit in the array


void displayCount(int array[], int size)

{

double sum=0;

for(int i=0;i<size;i++)

sum=sum+array[i];


cout<<"Digit Count Percentage"<<endl;

cout<<"-----------------------------------------------------------"<<endl;


printf("One %d %.1f%% ",array[0],(array[0]*100.0/sum));

printf("Two %d %.1f%% ",array[1],(array[1]*100.0/sum));

printf("Three %d %.1f%% ",array[2],(array[2]*100.0/sum));

printf("Four %d %.1f%% ",array[3],(array[3]*100.0/sum));

printf("Five %d %.1f%% ",array[4],(array[4]*100.0/sum));

printf("Six %d %.1f%% ",array[5],(array[5]*100.0/sum));

printf("Seven %d %.1f%% ",array[6],(array[6]*100.0/sum));

printf("Eight %d %.1f%% ",array[7],(array[7]*100.0/sum));

printf("Nine %d %.1f%% ",array[8],(array[8]*100.0/sum));

}



int main()

{

int num;

int arr[9];

for(int i=0;i<9;i++)

arr[i]=0;


ifstream inputFile("input.txt");

if (inputFile.is_open())

{

while ( inputFile.good() )

{

inputFile>>num;

while(num>0)

{

digitCount(arr,9,rstDigit(num));

num=num/10;

}

}

}

displayCount(arr,9);

return 0;

}