In: Computer Science
Write a program IN C that reads all integers that are in the range of 0 to 100, inclusive from an input file named: a.txt and counts how many occurrences of each are in the file. After all input has been processed, display all the values with the number of occurrences that were in are in the input file.
Note: The program ignores any number less than 0 or greater than 100.
Note: Do not display zero if a number is not in the file.
Hints: An array of size 101 is good enough. A number in the file plays the role of an index.
For example: Suppose the content of the file: a.txt is as
follows:
99 2 99
3
-12 80 12 33
3 99 100 1234 84
The display output is:
2 has occurred: 1 times
3 has occurred: 2 times
12 has occurred: 1 times
33 has occurred: 1 times
80 has occurred: 1 times
84 has occurred: 1 times
99 has occurred: 3 times
100 has occurred: 1 times
Note that this is just a sample dialog. Your program should work
for any number of data values and you MUST match
the sample dialog as well.
/*
* C Program to count number of occurence of 0-100 numbers in text file
*/
#include <stdio.h>
#define MAX 101
int main()
{
int i, num;
int numbers[MAX] = {0};
FILE *fRead;
fRead = fopen("a.txt", "r");
if (fRead == NULL)
{
printf("File not found\n");
}
else
{
while (!feof(fRead))
{
fscanf(fRead, "%d", &num);
if (num >= 0 && num <= 100)
numbers[num] += 1;
}
for (i = 0; i < MAX; i++)
{
if (numbers[i] != 0)
{
printf("%d has occured: %d times\n", i, numbers[i]);
}
}
}
fclose(fRead);
return 0;
}
