programming in C Create and display a histogram using the va
programming in C:
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
Solution
// Program is to open a file and creating a histogram using the values
#include <stdio.h>
#include <stdlib.h>
int main()
{
static char digitCount[10];
char fileName[32];
int totalValues = 0,ch;
printf (\" Enter file Name ::\\t\");
gets(fileName); // Reading file name from user
FILE *fp ; // Pointer to read the file
if ((fp = fopen(fileName, \"r\")) == NULL) // Reading the file
{
printf(\"Error! File Not found \ \ \");
exit(1); // Program exits if file pointer returns NULL.
}
ch = getc(fp);
while (ch != EOF) // looping until end of the file
{
if (ch >= \'0\' && ch <= \'9\'){ // Only consider digit values
digitCount[ch-48] = digitCount[ch-48] + 1; // Counting the values
totalValues += 1;
}
ch = getc(fp);
}
printf(\" Total number of values in list is ::\\t%d\ \",totalValues);
for (ch =0 ; ch<10;ch++){ // Printing the count of each digit
printf (\" %d digit count :: %d \ \",ch,digitCount[ch]);
}
fclose(fp); // Closing the file
return 0;
}
