20.5k views
4 votes
In c please

Counting the character occurrences in a file
For this task you are asked to write a program that will open a file called “story.txt
and count the number of occurrences of each letter from the alphabet in this file.
At the end your program will output the following report:
Number of occurrences for the alphabets:
a was used-times.
b was used - times.
c was used - times .... ...and so, on
Assume the file contains only lower-case letters and for simplicity just a single
paragraph. Your program should keep a counter associated with each letter of the
alphabet (26 counters) [Hint: Use array|
| Your program should also print a histogram of characters count by adding
a new function print Histogram (int counters []). This function receives the
counters from the previous task and instead of printing the number of times each
character was used, prints a histogram of the counters. An example histogram for
three letters is shown below) [Hint: Use the extended asci character 254]:

User Erik Z
by
3.5k points

1 Answer

4 votes

Answer:

#include <stdio.h>

#include <ctype.h>

void printHistogram(int counters[]) {

int largest = 0;

int row,i;

for (i = 0; i < 26; i++) {

if (counters[i] > largest) {

largest = counters[i];

}

}

for (row = largest; row > 0; row--) {

for (i = 0; i < 26; i++) {

if (counters[i] >= row) {

putchar(254);

}

else {

putchar(32);

}

putchar(32);

}

putchar('\\');

}

for (i = 0; i < 26; i++) {

putchar('a' + i);

putchar(32);

}

}

int main() {

int counters[26] = { 0 };

int i;

char c;

FILE* f;

fopen_s(&f, "story.txt", "r");

while (!feof(f)) {

c = tolower(fgetc(f));

if (c >= 'a' && c <= 'z') {

counters[c-'a']++;

}

}

for (i = 0; i < 26; i++) {

printf("%c was used %d times.\\", 'a'+i, counters[i]);

}

printf("\\Here is a histogram:\\");

printHistogram(counters);

}

In c please Counting the character occurrences in a file For this task you are asked-example-1
In c please Counting the character occurrences in a file For this task you are asked-example-2
In c please Counting the character occurrences in a file For this task you are asked-example-3
In c please Counting the character occurrences in a file For this task you are asked-example-4
User Dhaval Shukla
by
4.4k points