08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 ■ Arrays

This prints a letter (in lowercase) followed by its count. Let us see how. The code for 'a' is 97.

When n is 1,

'a' + n - 1

is evaluated as 97+1-1, which is 97; when 97 is printed with %c, it is interpreted as a character,

so the letter a is printed. When n is 2,

'a' + n - 1

is evaluated as 97+2-1, which is 98; when 98 is printed with %c, it is interpreted as a character,

so b is printed. When n is 3,

'a' + n - 1

is evaluated as 97+3-1, which is 99; when 99 is printed with %c, it is interpreted as a character,

so c is printed. And so on. As n takes on the values from 1 to 26,

'a' + n - 1

will take on the codes for the letters from 'a' to 'z'.

As a matter of interest, we could have used the following special form of the for statement

described earlier to achieve the same result. Here it is:

for (ch = 'a', n = 1; n <= 26; ch++, n++)

fprintf(out, "%4c %8d\n", ch, letterCount[n]);

The loop is still executed with n going from 1 to 26. But, in sync with n, it is also executed with

ch going from 'a' to 'z'. Note the use of ch++ to move on to the next character.

8.6 Making Better Use of fopen

Consider the statement:

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

This says to “open the file passage.txt for reading.” It assumes that the file has been created

and the appropriate data stored in it. But what if the user forgot to create the file or has put it in

the wrong place (the wrong folder, for instance)? We can use fopen to check for this. If fopen

cannot find the file, it returns the predefined value NULL (defined in stdio.h). We can test for this

as follows:

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

if (in == NULL) {

printf("File cannot be found\n");

exit(1);

}

209

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!