Create and display a histogram using the values in a file 1
Solution
//Programme code begins
#include <stdio.h>
#define SIZE 100
int main()
{
char filename[SIZE]; // holds filename
//varible declarations
FILE *fptr; //pointer declaration
int c,counter;
int a[10]={0},other=0,i,j,numberArray[100];
printf(\"Enter file name : \ \");
scanf(\"%s\",filename);
// file opeing error in case any problem
if ((fptr = fopen(filename, \"r\")) == NULL)
{
printf(\"Error! opening file\");
return 0;
}
else
printf(\"Success Reading file data : \ \");
while(1) //loop to find each digit counts
{
counter = fscanf(fptr, \"%d\", &c); //read data in integer form
if(counter==1) //if counter not equal to 1 then EOF occurs
{
//else if ladder for each digit occurences finding
if (c == 0 )
{
a[0]=a[0]+1;
}
else if (c==1)
{
a[1]=a[1]+1;
}
else if (c==2)
{
a[2]=a[2]+1;
}
else if (c==3)
{
a[3]=a[3]+1;
}
else if (c==4)
{
a[4]=a[4]+1;
}
else if (c==5)
{
a[5]=a[5]+1;
}
else if (c==6)
{
a[6]=a[6]+1;
}
else if (c==7)
{
a[7]=a[7]+1;
}
else if (c==8)
{
a[8]=a[8]+1;
}
else if (c==9)
{
a[9]=a[9]+1;
}
else
other=other++;
}
else
{
break; //if EOF occures break the loop
}
}
//LOOP FOR DISPLAY OUTPUT IN HISTOGRAM FORM
printf(\"Number\\t\\t Count \ \");
for(i=0; i <= 9; i++)
{
printf(\"%9d%15d \", i, a[i]);
// the inner for loop, for every row, read column by column and print the bar...
for(j = 1; j<= a[i]; j++)
// print the asterisk bar...repeat...
printf(\"*\");
// go to new line for new row...repeats...
printf(\"\ \");
}
return 0;
}
Output :
Enter file name :
ashok.txt
Success Reading file data :
Number Count
0 0
1 1 *
2 1 *
3 1 *
4 1 *
5 1 *
6 1 *
7 1 *
8 1 *
9 1 *


