CSM217: C for Computer Scientists

Lecture 4: Exercise 1: Solution


#include <stdio.h>
#include <ctype.h>

main() {
 int a = 0;
 
 for(a=0; a < 128; a++) {
  printf("ASCII %d is %s %c\n", a, isprint(a)? "character" : "unprintable", isprint(a)?a:'\b');
 }
}
Explanation of the printf statement

The positional argument %d causes the value of a to be printed as an integer. This is required because we want to print a as though it's an ASCII value.

The conditional expression isprint(a) ? "character" : "unprintable" tests if a is a printable character, and if it is it causes the string "character" to be used as the value of the second positional arugment in the print format (%s). Otherwise, the string "unprintable" is used.

Finally, the last conditional expression isprint(a) ? a : '\b' again checks the printability of a. If it is printable, then the value of a is printed as a character, otherwise we print a backspace character (we could also have printed a null character).