O'Reilly logo

C Primer Plus, Fourth Edition by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Programming Exercises

  1. Rewrite the program in Listing 12.4 so that it does not use global variables.

  2. Gasoline consumption commonly is computed in miles per gallon in the U.S. and in liters per 100 kilometers in Europe. What follows is part of a program that asks the user to choose a mode (metric or US), and then gathers data and computes fuel consumption:

    // pe12-x1.c
    #include <stdio.h>
    #include "pe12-2a.h"
    int main(void)
    {
      int mode;
    
      printf("Enter 0 for metric mode, 1 for US mode: ");
      scanf("%d", &mode);
      while (mode >= 0)
      {
         set_mode(mode);
         get_info();
         show_info();
         printf("Enter 0 for metric mode, 1 for US mode");
         printf(" (-1 to quit): ");
         scanf("%d", &mode);
      }
      printf("Done.\n");
      return 0;
    }
    

    Here is some sample output:

     Enter 0 for metric mode, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required