08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8 ■ Arrays

The complete program is shown as Program P8.2. It reads data from the file passage.txt and

sends output to the file output.txt.

Program P8.2

#include <stdio.h>

#include <ctype.h>

int main() {

char ch;

int n, letterCount[27], position(char);

FILE * in = fopen("passage.txt", "r");

FILE * out = fopen("output.txt", "w");

for (n = 1; n <= 26; n++) letterCount[n] = 0; //set counts to 0

while ((ch = getc(in)) != EOF) {

n = position(ch);

if (n > 0) ++letterCount[n];

}

//print the results

fprintf(out, "Letter Frequency\n\n");

for (n = 1; n <= 26; n++)

fprintf(out, "%4c %8d\n", 'a' + n - 1, letterCount[n]);

fclose(in);

fclose(out);

} //end main

int position(char ch) {

if (isupper(ch)) return ch - 'A' + 1;

if (islower(ch)) return ch - 'a' + 1;

return 0;

} //end position

Suppose passage.txt contains the following:

The quick brown fox jumps over the lazy dog.

If the quick brown fox jumped over the lazy dog then

Why did the quick brown fox jump over the lazy dog?

207

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!