In C coding: Create and display a histogram using the values in a file 1) Prompt
ID: 3816155 • Letter: I
Question
In C coding:
Create and display a histogram using the values in a file
1) Prompt the user for a filename
2) Open that file and read the integers from the file (each integer will be between 0 and 9, inclusive)
3) we want to count how many times each of the values between 0 and 9 appears in the file
4) then display the total number of values read from the file, and how many times each particular value was in the file
Inclide a testbench and detailed comments and make sure pointers initialized to NULL when declared
Explanation / Answer
#include <stdio.h>
#include<stdlib.h>
main()
{
int numArr[50]; int freq[50];
int i,count,j;
char fname[20];
FILE *myFile = NULL;
printf("enter the fnae ");
scanf("%s",fname);
myFile = fopen(fname, "r");
i=0;
count=0;
while( fscanf(myFile, "%d,", &numArr[i]) > 0 ) //reading numbers from file to array
{
count++;
i++;
}
for(i=0;i<count;i++) //initially all frequencies are zero
freq[i]=0;
for(i=0;i<count;i++) // getting the frequencies of numbers
freq[numArr[i]] += 1;
printf("%s%13s%12s ","Element", "Frequency", "Histogram");
for(i=0; i <= 9; i++)
{
printf("%4d%12d ", i, freq[i]);
for(j = 1; j<= freq[i]; j++)
// printing the histogram with * as one unit
printf("*");
printf(" ");
}
fclose(myFile);
}