-- Programming Language Books and Training

 C C++ Java

Books by K. N. King

Books by K. N. King
Short courses
Recommended books
Recommended links

C Programming: A Modern Approach (Second Edition)

Chapter 7

Answers to Selected Exercises

3. [was #4] (b) is not legal.

4. [was #6] (d) is illegal, since printf requires a string, not a character, as its first argument.

10. [was #14] unsigned int, because the (int) cast applies only to j, not j * k.

12. [was #16] The value of i is converted to float and added to f, then the result is converted to double and stored in d.

14. [was #18] No. Converting f to int will fail if the value stored in f exceeds the largest value of type int.

Answers to Selected Programming Projects

1. [was #2] short int values are usually stored in 16 bits, causing failure at 182. int and long int values are usually stored in 32 bits, with failure occurring at 46341.

2. [was #8]

#include <stdio.h>

int main(void)
  int i, n;
  char ch;

  printf("This program prints a table of squares.\n");
  printf("Enter number of entries in table: ");
  scanf("%d", &n);
  ch = getchar();
    /* dispose of new-line character following number of entries */
    /* could simply be getchar(); */

  for (i = 1; i <= n; i++) {
    printf("%10d%10d\n", i, i * i);
    if (i % 24 == 0) {
      printf("Press Enter to continue...");
      ch = getchar();   /* or simply getchar(); */

  return 0;

5. [was #10]

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

int main(void)
  int sum = 0;
  char ch;

  printf("Enter a word: ");

  while ((ch = getchar()) != '\n')
    switch (toupper(ch)) {
      case 'D': case 'G':
        sum += 2; break;
      case 'B': case 'C': case 'M': case 'P':
        sum += 3; break;
      case 'F': case 'H': case 'V': case 'W': case 'Y':
        sum += 4; break;
      case 'K':
        sum += 5; break;
      case 'J': case 'X':
        sum += 8; break;
      case 'Q': case 'Z':
        sum += 10; break;
        sum++; break;

  printf("Scrabble value: %d\n", sum);

  return 0;

6. [was #12]

#include <stdio.h>

int main(void)
  printf("Size of int: %d\n", (int) sizeof(int));
  printf("Size of short: %d\n", (int) sizeof(short));
  printf("Size of long: %d\n", (int) sizeof(long));
  printf("Size of float: %d\n", (int) sizeof(float));
  printf("Size of double: %d\n", (int) sizeof(double));
  printf("Size of long double: %d\n", (int) sizeof(long double));

  return 0;

Since the type of a sizeof expression may vary from one implementation to another, it's necessary in C89 to cast sizeof expressions to a known type before printing them. The sizes of the basic types are small numbers, so it's safe to cast them to int. (In general, however, it's best to cast sizeof expressions to unsigned long and print them using %lu.) In C99, we can avoid the cast by using the %zu conversion specification.

Copyright © 2008, 1996 W. W. Norton & Company, Inc. All rights reserved.