NEW C PRIMER PLUS SECOND EDITION by Waite & Prata
CHAPTER 9 NOTES by Linda Buck
Copyright (C) 1993 by The Waite Group
Copyright (C) 1997 by Linda Buck


 1. Functions
    ---------
    Form:
    (1) Function Prototype
        return_type func_name(type formal_arg1, type formal_arg2, ... );
    (2) Function Call
        ... func_name(actual_arg1, actual_arg2, ... ) ...
    (3) Function Definition
        return_type func_name(type formal_arg1, type formal_arg2, ... )
        {
                ...
          return expression;
                ...
        }

    Meaning of Function Call:
    (1) Remember location of function call.
    (2) Evaluate call's actual arguments and copy these values into
        function's formal arguments which are local variables.
    (3) Go to function's first statement.
    (4) Execute function's code until you encounter a return statement
        or the closing }.
    (5) Return to the point of the function call.  If there is a return
        value return this value to the point of the function call.
    (6) Continue executing the calling program from the point of the
        function call.

    Note:
    (1) There should be a function prototype for every function in your
        program except main() at the top of your source code file.
    (2) If there are no formal arguments use the keyword void.
    (3) Actual arguments can be constants, variables, or expressions.
    (4) When a function is called the actual arguments are evaluated
        and their values are copied into the formal arguments.
    (5) Formal arguments and variables declared inside a function are
        local variables.  This means they are known only inside the
        function in which they are declared.
    (6) (a) If there is no return type use the keyword void.  In this
            case you may omit the return statement -- the compiler will
            automatically supply one just before the closing }.  If you
            use a return statement omit the expression.
        (b) If there is a return type then you must use a return
            statement with an expression that evaluates to the return
            type.
        (c) More than one return statement can be used in a function.
    (7) You can use a function call anywhere that you can use an
        expression.

    Programs With More Than One Function:
    (1) When a program of several functions is put together, execution
        starts with the first statement in main().
    (2) Each C function in a program is on equal footing with the
        others.  Each can call any other function or be called by any
        other function.

    Usage:
    (1) Code
        Functions are used to avoid repeating code.
    (2) Design
        Functions are used to modularize code.

 2. Example 9.1
    -----------
    Program #1:
    /* func1.c -- shows simple functions */
    #include <stdio.h>
    void stars(void);              /* function prototype */
    void add(int num1, int num2);  /* function prototype */
    int main(void)
    {
      stars();    /* function call */
      add(1, 2);  /* function call */
      stars();    /* function call */
      return 0;
    }

    /* stars() function definition */
    /* stars() has no formal arguments */
    /* stars() returns no value */
    void stars(void)
    {
      printf("*************************\n");
    }

    /* add() function definition */
    /* num1, num2 are formal arguments and local variables */
    /* add() returns no value */
    void add(int num1, int num2)
    {
      printf("The sum of %d and %d is %d.\n", num1, num2, num1+num2);
    }

    Output #1:
    *************************
    The sum of 1 and 2 is 3.
    *************************

    Program #2:
    /* func2.c -- shows simple functions */
    #include <stdio.h>
    void chars(char ch, int n);        /* function prototype */
    void average(int num1, int num2);  /* function prototype */
    int main(void)
    {
      chars('+', 15);  /* function call */
      average(3, 4);   /* function call */
      chars('*', 25);  /* function call */
      return 0;
    }

    /* chars() function definition */
    /* ch, n are formal arguments and local variables */
    /* chars() returns no value */
    void chars(char ch, int n)
    {
      int i;  /* local variable */

      for (i = 1; i <= n; i++)
        putchar(ch);
      putchar('\n');
    }

    /* average() function defintion */
    /* num1, num2 are formal arguments and local variables */
    /* average() returns no value */
    void average(int num1, int num2)
    {
      printf("The average of %d and %d is %.2lf.\n", num1, num2,
        (num1+num2)/2.0);
    }

    Output #2:
    +++++++++++++++
    The average of 3 and 4 is 3.50.
    *************************

 3. Example 9.2
    -----------
    Program:
    /* func3.c -- shows functions with arguments */
    #include <stdio.h>
    void add(int num1, int num2);  /* function prototype */
    int main(void)
    {
      int a, b, c, d;

      /* (1) actual arguments can be constants, variables, or
             expressions
         (2) when a function is called the actual arguments are
             evaluated and their values are copied into the formal
             arguments */
      add(1, 3);  /* function call */

      a = 5; b = 7;
      printf("\nmain(): a = %d, b = %d\n", a, b);      
      add(a, b);  /* function call */

      a = 5; b = 7; c = 9; d = 11;
      printf("\nmain(): a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
      add(a+b, c+d);  /* function call */
      return 0;
    }

    /* add() function definition */
    /* num1, num2 are formal arguments and local variables */
    /* add() returns no value */
    void add(int num1, int num2)
    {
      printf("add(): num1 = %d, num2 = %d\n", num1, num2);
      printf("add(): sum = %d\n", num1 + num2);
    }

    Output:
    add(): num1 = 1, num2 = 3
    add(): sum = 4

    main(): a = 5, b = 7
    add(): num1 = 5, num2 = 7
    add(): sum = 12

    main(): a = 5, b = 7, c = 9, d = 11
    add(): num1 = 12, num2 = 20
    add(): sum = 32

 4. Example 9.3
    -----------
    Program #1:
    /* func4.c -- shows local variables */
    #include <stdio.h>
    void func(void);  /* function prototype */
    int main(void)
    {
       int a;

       /* formal arguments and variables declared inside a function are
          local variables --  this means they are known only inside the
          function in which they are declared */
       a = 1;
       printf("main(): a = %d\n", a);
       func();  /* function call */
       printf("main(): a = %d\n", a);
       return 0;
    }

    /* func() function definition */
    /* func() has no formal arguments */
    /* func() returns no value */
    void func(void)
    {
      int a;  /* local variable */

      printf("func(): a = %d\n", a);
      a = 5;
      printf("func(): a = %d\n", a);
    }

    Output #1:
    main(): a = 1
    func(): a = 69
    func(): a = 5
    main(): a = 1

    Program #2:
    /* func5.c -- shows local variables */
    #include <stdio.h>
    void func(int a);  /* function prototype */
    int main(void)
    {
      int a;

      /* formal arguments and variables declared inside a function are
         local variables -- this means they are known only inside the
         function in which they are declared */
      a = 1;
      printf("main(): a = %d\n", a);
      func(a);  /* function call */
      printf("main(): a = %d\n", a);
      return 0;
    }

    /* func() function definition */
    /* a is a formal argument and a local variable */
    /* func() has no return value */
    void func(int a)
    {
      printf("func(): a = %d\n", a);
      a = 5;
      printf("func(): a = %d\n", a);
    }

    Output #2:
    main(): a = 1
    func(): a = 1
    func(): a = 5
    main(): a = 1

    Program #3:
    /* func6.c -- shows local variables */
    #include <stdio.h>
    void func(int a);  /* function prototype */
    int main(void)
    {
      int a, b;
 
      /* formal arguments and variables declared inside a function are
         local variables -- this means they are known only inside the
         function in which they are declared */
      a = 1; b = 3;
      printf("main(): a = %d, b = %d\n", a, b);
      func(a);  /* function call */
      printf("main(): a = %d, b = %d\n", a, b);

      a = 1; b = 3;
      printf("\nmain(): a = %d, b = %d\n", a, b);
      func(b);  /* function call */
      printf("main(): a = %d, b = %d\n", a, b);
      return 0;
    }

    /* func() function definition */
    /* a is a formal argument and a local variable */
    /* func() returns no value */
    void func(int a)
    {
      int b;

      printf("func(): a = %d, b = %d\n", a, b);
      a = 5;
      b = 7;
      printf("func(): a = %d, b = %d\n", a, b);
    }

    Output #3:
    main(): a = 1, b = 3
    func(): a = 1, b = 129
    func(): a = 5, b = 7
    main(): a = 1, b = 3

    main(): a = 1, b = 3
    func(): a = 3, b = 129
    func(): a = 5, b = 7
    main(): a = 1, b = 3

 5. Example 9.4
    -----------
    Program:
    /* func7.c -- shows functions with a return value */
    int imin1(int num1, int num2);  /* function prototype */
    int imin2(int num1, int num2);  /* function prototype */
    int imin3(int num1, int num2);  /* function prototype */
    int main(void)
    {
      int result;

      result = imin1(1, 3);
      printf("result = %d\n", result);
      result = imin1(7, 5);
      printf("result = %d\n", result);

      result = imin2(1, 3);
      printf("\nresult = %d\n", result);
      result = imin2(7, 5);
      printf("result = %d\n", result);

      result = imin3(1, 3);
      printf("\nresult = %d\n", result);
      result = imin3(7, 5);
      printf("result = %d\n", result);
      return 0;
    }

    /* imin1() function definition */
    /* num1, num2 are formal arguments and local variables */
    /* imin1() returns an int value */
    int imin1(int num1, int num2)
    {
      int min;  /* local variable */

      if (num1 < num2)
        min = num1;
      else
        min = num2;
      return min;  /* returns a value */
    }

    /* imin2() function definition */
    /* num1, num2 are formal arguments and local variables */
    /* imin2() returns an int value */
    int imin2(int num1, int num2)
    {
      /* returns the value of an expression */
      return (num1 < num2) ? num1 : num2;
    }

    /* imin3() function definition */
    /* num1, num2 are formal arguments and local variables */
    /* imin3() returns an int value */
    int imin3(int num1, int num2)
    {
      /* more than one return statement can be used in a function */
      if (num1 < num2)
        return num1;  /* returns a value */
      else
        return num2;  /* returns a value */
    }

    Output:
    result = 1
    result = 5

    result = 1
    result = 5

    result = 1
    result = 5

 6. Example 9.5
    -----------
    Program:
    /* func8.c -- shows function calls */
    #include <stdio.h>
    double inverse(double num);  /* function prototype */
    int main(void)
    {
      double result;

      /* you can use a function call anywhere that you can use an
         expression */
      result = inverse(2.0);  /* function call */
      printf("result = %.2lf\n", result);

      printf("result = %.2lf\n", inverse(4.0));
        /* function call */

      result = inverse(2.0) + inverse(4.0); /* function calls */
      printf("result = %.2lf\n", result);
      return 0;
    }

    /* inverse() function definition */
    /* num is a formal argument and a local variable */
    /* inverse() returns a double value */
    double inverse(double num)
    {
      return 1.0/num;
    }

    Output:
    result = 0.50
    result = 0.25
    result = 0.75

 7. Function Declarations and Function Prototypes
    ---------------------------------------------
    (1) The compiler needs to know the return type of a function so that
        when a function is called it can supply any necessary automatic
        type conversions.  This means either the function definition,
        the function declaration, or the function prototype must appear
        before a function is called.
    (2) A function declaration states the return type.
    (3) A function prototype states the return type, the type of each
        argument, and optionally, the variable names.
    (4) When a function prototype is used the compiler does argument
        error checking.  Warning messages are issued, and when a type
        mismatch is found, the compiler automatically performs a type
        cast to convert the actual argument to the same type as the
        formal argument.
    (5) When you give a function declaration with no arguments the
        compiler does no argument error checking.
        Example:
        int print_name(); -- arguments not specified
                             no argument error checking
    (6) In a function prototype where the function has no arguments use
        the keyword void within the parentheses.  The compiler will then
        do argument error checking.
        Example:
        int print_name(void); -- no arguments
                                 argument error checking

 8. Example 9.6
    -----------
    Program #1:
    /* declare.c -- uses a function declaration */
    #include <stdio.h>
    int imax();  /* function declaration */
      /* arguments not specified -- no argument error checking */
    int main(void)
    {
      printf("The maximum of %d and %d is %d.\n",
        3, 5, imax(3));         /* too few arguments */
      printf("The maximum of %d and %d is %d.\n",
        3, 5, imax(3.0, 5.0));  /* arguments are wrong type */
      return 0;
    }

    int imax(int num1, int num2)
    {
      int max;

      if (num1 > num2)
        max = num1;
      else
        max = num2;
      return max;
    }

    Output #1:
    The maximum of 3 and 5 is 313.
    The maximum of 3 and 5 is 0.

    Program #2:
    /* proto.c -- uses a function prototype */
    #include <stdio.h>
    int imax(int num1, int num2);  /* function prototype */
      /* arguments specified -- argument error checking done */
    int main(void)
    {
      printf("The maximum of %d and %d is %d.\n",
        3, 5, imax(3));
      /* compiler gives the following warning message:
         'imax' : too few actual parameters */
      printf("The maximum of %d and %d is %d.\n",
        3, 5, imax(3.0, 5.0));
      /* compiler gives the following warning messages:
         long/short mismatch in argument : conversion supplied
         long/short mismatch in argument : conversion supplied */
      return 0;
    }

    int imax(int num1, int num2)
    {
      int max;

      if (num1 > num2)
        max = num1;
      else
        max = num2;
      return max;
    }

    Output #2:
    The maximum of 3 and 5 is 289.
    The maximum of 3 and 5 is 5.

 9. Example 9.7
    -----------
    Problem:
    Write and test a function that calculates the factorial of a number.

    Algorithm:
    n! = n x (n-1) x ... x 3 x 2 x 1

    Program:
    /* factor1.c -- calculates factorial of a number */
    #include <stdio.h>
    long fact(int n);
    int main(void)
    {
      int num;

      printf("This program calculates the factorial of a number.\n");
      while (1)
      {
        printf("\nPlease enter a positive integer less than 16.\n");
        printf("Type q to quit.\n");     
        if (scanf("%d", &num) != 1)
          break;
        if (num < 0 || num > 15)
        {
          printf("Error: 0 <= integer <= 15.\n");
          continue;
        }
        printf("%d! = %ld\n", num, fact(num));
      }
      return 0;
    }

    long fact(int n)
    {
      long ans;

      for (ans = 1; n > 1; n--)
        ans *= n;
      return ans;
    }

    Screen:
    Output: This program calculates the factorial of a number.
    Output:
    Output: Please enter a positive integer less than 16.
    Output: Type q to quit.
    Input:  4
    Output: 4! = 24
    Output:
    Output: Please enter a positive integer less than 16.
    Output: Type q to quit.
    Input:  6
    Output: 6! = 720
    Output:
    Output: Please enter a positive integer less than 16.
    Output: Type q to quit.
    Input:  q

10. Example 9.8
    ------------
    Problem:
    Write and test a function that raises a number to a positive integer
    power.

    Program:
    /* power.c -- raises a number to a positive integer power */
    #include <stdio.h>
    double power(double num, int exp);
    int main(void)
    {
      double x;
      int y;

      printf("This program raises a number to a positive integer "
        "power.\n");
      while (1)
      {
        printf("\nPlease enter a number and a positive integer "
          "power.\n");
        printf("Type q to quit.\n");
        if (scanf("%lf %d", &x, &y) != 2)
          break;
        if (y < 0)
        {
          printf("Error: power must be positive.\n");
          continue;
        }
        printf("The number %.3le raised to the power %d is %.3le.\n",
          x, y, power(x, y));
      }
      return 0;
    }

    double power(double num, int exp)
    {
      int i;
      double pow;

      for (i = 1, pow = 1.0; i <= exp; i++)
        pow *= num;
      return pow;
    }

    Screen:
    Output: This program raises a number to a positive integer power.
    Output:
    Output: Please enter a number and a positive integer power.
    Output: Type q to quit.
    Input:  2.5 0
    Output: The number 2.500e+000 raised to the power 0 is 1.000e+000.
    Output:
    Output: Please enter a number and a positive integer power.
    Output: Type q to quit.
    Input:  2.5 3
    Output: The number 2.500e+000 raised to the power 3 is 1.563e+001.
    Output:
    Output: Please enter a number and a positive integer power.
    Output: Type q to quit.
    Input:  2.5 -3
    Output: Error: power must be positive.
    Output:
    Output: Please enter a number and a positive integer power.
    Output: Type q to quit.
    Input:  3.5 6
    Output: The number 3.500e+000 raised to the power 6 is 1.838e+003.
    Output:
    Output: Please enter a number and a positive integer power.
    Output: Type q to quit.
    Input:  q

11. Example 9.9
    -----------
    Problem:
    Write and test a function that prints a character using a number of
    rows and columns.

    Program:
    /* rect.c -- prints a character using a number of rows and
                 columns */
    #include <stdio.h>
    #define MAXCOLS 80
    void print_rectangle(char ch, int rows, int cols);
    int main(void)
    {
      char ch;
      int rows, cols;

      printf("This program prints a character using a number of\n");
      printf("rows and columns.\n");
      while (1)
      {
        /* prompt user for input */
        printf("\nPlease enter a character, a number of rows, and a\n");
        printf("number of columns.  Type EOF to quit.\n");

        /* get input and handle quit case */
        if (scanf("%c %d %d", &ch, &rows, &cols) != 3)
          break;

        /* clear input buffer */
        while (getchar() != '\n');

        /* handle invalid input */
        if (rows < 1 || cols < 1 || cols > MAXCOLS)
        {
          printf("Error: invalid input.\n");
          continue;
        }

        /* print character using number of rows and columns */
        print_rectangle(ch, rows, cols);
      }
      return 0;
    }

    void print_rectangle(char ch, int rows, int cols)
    {
      int row, col;

      for (row = 1; row <= rows; row++)
      {
        for (col = 1; col <= cols; col++)
          putchar(ch);
        putchar('\n');
      }
    }

    Screen:
    Output: This program prints a character using a number of
    Output: rows and columns.
    Output:
    Output: Please enter a character, a number of rows, and a
    Output: number of columns.  Type EOF to quit.
    Input:  a 2 3
    Output: aaa
    Output: aaa
    Output:
    Output: Please enter a character, a number of rows, and a
    Output: number of columns.  Type EOF to quit.
    Input:  b 5 90
    Output: Error: invalid input.
    Output:
    Output: Please enter a character, a number of rows, and a
    Output: number of columns.  Type EOF to quit.
    Input:  b 5 4
    Output: bbbb
    Output: bbbb
    Output: bbbb
    Output: bbbb
    Output: bbbb
    Output:
    Output: Please enter a character, a number of rows, and a
    Output: number of columns.  Type EOF to quit.
    Input:  [Ctrl-Z] (Unix: [Ctrl-D])

12. Example 9.10
    ------------
    Problem:
    Write and test a function that gets a lowercase letter.  Have the
    function retry for invalid input, and have the function return EOF
    for end-of-file.

    Program:
    /* getlower.c -- gets lowercase letters */
    #include <stdio.h>
    int get_lower(void);
    int main(void)
    {
      int lower;

      printf("This program gets lowercase letters.\n");
      while ((lower = get_lower()) != EOF)
        printf("lowercase letter = '%c'\n", lower);
      return 0;
    }
    
    int get_lower(void)
    {
      int letter;

      /* prompt user for lowercase letter */
      printf("\nPlease enter a lowercase letter.  Type EOF to quit.\n");

      /* get valid lowercase letter loop */
      /* get lowercase letter and handle EOF */
      while ((letter = getchar()) != EOF)
      {
        /* clear input buffer */
        if (letter != '\n')
          while (getchar() != '\n');

        /* handle valid lowercase letter */
        if (letter >= 'a' && letter <= 'z')
          break;

        /* handle invalid lowercase letter */
        printf("Error: invalid lowercase letter.  Please retry.\n");
      }

      /* return valid lowercase letter */
      return letter;
    }

    Screen:
    Output: This program gets lowercase letters.
    Output:
    Output: Please enter a lowercase letter.
    Input:  a
    Output: lowercase letter = 'a'
    Output:
    Output: Please enter a lowercase letter.
    Input:  b
    Output: lowercase letter = 'b'
    Output:
    Output: Please enter a lowercase letter.
    Input:  c
    Output: lowercase letter = 'c'
    Output:
    Output: Please enter a lowercase letter.
    Input:  abc
    Output: lowercase letter = 'a'
    Output:
    Output: Please enter a lowercase letter.
    Input:  XYZ
    Output: Error: invalid lowercase letter.  Please retry.
    Input:  d
    Output: lowercase letter = 'd'
    Output:
    Output: Please enter a lowercase letter.
    Input:  [Ctrl-Z] (Unix: [Ctrl-D])

13. Example 9.11
    ------------
    Problem:
    Write and test a function that gets a positive integer.  Have the
    function retry for invalid input, and have the function return -1
    for end-of-file.

    Program:
    /* getpint.c -- gets positive integers */
    #include <stdio.h>
    int get_posint(void);
    int main(void)
    {
      int pos;

      printf("This program gets positive integers.\n");
      while ((pos = get_posint()) >= 0)
        printf("positive integer = %d\n", pos);
      return 0;
    }

    int get_posint(void)
    {
      int status, num;

      /* prompt user for positive integer */
      printf("\nPlease enter a positive integer.  Type EOF to quit.\n");

      /* get valid positive integer loop */
      while (1)
      {
        /* get positive integer and handle EOF */
        if ((status = scanf("%d", &num)) == EOF)
        {
          num = -1;
          break;
        }

        /* clear input buffer */
        while (getchar() != '\n');

        /* handle valid positive integer */
        if (status == 1 && num >= 0)
          break;

        /* handle invalid positive integer */
        printf("Error: invalid positive integer.  Please retry.\n");
      }

      /* return valid positive integer */
      return num;
    }

    Screen:
    Output: This program gets positive integers.
    Output:
    Output: Please enter a positive integer.
    Input:  1
    Output: positive integer = 1
    Output:
    Output: Please enter a positive integer.
    Input:  2
    Output: positive integer = 2
    Output:
    Output: Please enter a positive integer.
    Input:  3
    Output: positive integer = 3
    Output:
    Output: Please enter a positive integer.
    Input:  1abc
    Output: positive integer = 1
    Output:
    Output: Please enter a positive integer.
    Input:  -1
    Output: Error: invalid positive integer.  Please retry.
    Input:  xyz
    Output: Error: invalid positive integer.  Please retry.
    Input:  4
    Output: positive integer = 4
    Output:
    Output: Please enter a positive integer.
    Input:  [Ctrl-Z] (Unix: [Ctrl-D])

14. Example 9.12
    ------------
    Problem:
    Write a general character menu program using a function.

    Program:
    /* menu1.c -- general character menu */
    #include <stdio.h>
    #define LAST_CHOICE 'd'
    int get_choice(void);
    int main(void)
    {
      int choice;

      printf("This is a general character menu program.\n");

      while ((choice = get_choice()) != LAST_CHOICE)
      {
        switch (choice)
        {
          case 'a':
            printf("Doing choice a action.\n");
            break;
          case 'b':
            printf("Doing choice b action.\n");
            break;
          case 'c':
            printf("Doing choice c action.\n");
            break;
        }
      }
      return 0;
    }

    int get_choice(void)
    {
      int choice;

      /* prompt user for menu choice */
      printf("\nPlease enter one of the following:\n");
      printf("a) choice a action\n");
      printf("b) choice b action\n");
      printf("c) choice c action\n");
      printf("d) quit\n");

      /* get valid menu choice loop */
      while (1)
      {
        /* get menu choice and handle EOF */
        if ((choice = getchar()) == EOF)
        {
          choice = LAST_CHOICE;
          break;
        }

        /* clear input buffer */
        if (choice != '\n')
          while (getchar() != '\n');

        /* handle valid menu choice */
        if (choice >= 'a' && choice <= LAST_CHOICE)
          break;

        /* handle invalid menu choice */
        printf("Error: invalid menu choice.  Please retry.\n");
      }

      /* return valid menu choice */
      return choice;
    }

    Screen:
    Output: This is a general character menu program.
    Output:
    Output: Please enter one of the following:
    Output: a) choice a action
    Output: b) choice b action
    Output: c) choice c action
    Output: d) quit
    Input:  a
    Output: Doing choice a action.
    Output:
    Output: Please enter one of the following:
    Output: a) choice a action
    Output: b) choice b action
    Output: c) choice c action
    Output: d) quit
    Input:  b
    Output: Doing choice b action.
    Output:
    Output: Please enter one of the following:
    Output: a) choice a action
    Output: b) choice b action
    Output: c) choice c action
    Output: d) quit
    Input:  c
    Output: Doing choice c action.
    Output:
    Output: Please enter one of the following:
    Output: a) choice a action
    Output: b) choice b action
    Output: c) choice c action
    Output: d) quit
    Input:  abc
    Output: Doing choice a action.
    Output:
    Output: Please enter one of the following:
    Output: a) choice a action
    Output: b) choice b action
    Output: c) choice c action
    Output: d) quit
    Input:  xyz
    Output: Error: invalid menu choice.  Please retry.
    Input:  d

15. Example 9.13
    ------------
    Problem:
    Write a general integer menu program using a function.

    Program:
    /* menu2.c -- general integer menu */
    #include <stdio.h>
    #define LAST_CHOICE 4
    int get_choice(void); 
    int main(void)
    {
      int choice;

      printf("This is a general integer menu program.\n");

      while ((choice = get_choice()) != LAST_CHOICE)
      {
        switch (choice)
        {
          case 1:
            printf("Doing choice 1 action.\n");
            break;
          case 2:
            printf("Doing choice 2 action.\n");
            break;
          case 3:
            printf("Doing choice 3 action.\n");
            break;
        }
      }
      return 0;
    }
     
    int get_choice(void)
    {
      int status, choice;

      /* prompt user for menu choice */
      printf("\nPlease enter one of the following:\n");
      printf("1) choice 1 action\n");
      printf("2) choice 2 action\n");
      printf("3) choice 3 action\n");
      printf("4) quit\n");

      /* get valid menu choice loop */
      while (1)
      {
        /* get menu choice and handle EOF */
        if ((status = scanf("%d", &choice)) == EOF)
        {
          choice = LAST_CHOICE;
          break;
        }

        /* clear input buffer */
        while (getchar() != '\n');

        /* handle valid menu choice */
        if (status == 1 && choice >= 1 && choice <= LAST_CHOICE)
          break;

        /* handle invalid menu choice */
        printf("Error: invalid menu choice.  Please retry.\n");
      }

      /* return valid menu choice */
      return choice;
    }

    Screen:
    Output: This is a general integer menu program.
    Output:
    Output: Please enter one of the following:
    Output: 1) choice 1 action
    Output: 2) choice 2 action
    Output: 3) choice 3 action
    Output: 4) quit
    Input:  1
    Output: Doing choice 1 action.
    Output:
    Output: Please enter one of the following:
    Output: 1) choice 1 action
    Output: 2) choice 2 action
    Output: 3) choice 3 action
    Output: 4) quit
    Input:  2
    Output: Doing choice 2 action.
    Output:
    Output: Please enter one of the following:
    Output: 1) choice 1 action
    Output: 2) choice 2 action
    Output: 3) choice 3 action
    Output: 4) quit
    Input:  3
    Output: Doing choice 3 action.
    Output:
    Output: Please enter one of the following:
    Output: 1) choice 1 action
    Output: 2) choice 2 action
    Output: 3) choice 3 action
    Output: 4) quit
    Input:  1abc
    Output: Doing choice 1 action.
    Output:
    Output: Please enter one of the following:
    Output: 1) choice 1 action
    Output: 2) choice 2 action
    Output: 3) choice 3 action
    Output: 4) quit
    Input:  5
    Output: Error: invalid menu choice.  Please retry.
    Input:  xyz
    Output: Error: invalid menu choice.  Please retry.
    Input:  4

16. Example 9.14
    ------------
    Problem:
    Suppose you manage a chain of four hotels.  Each hotel charges a
    different room rate, but all the rooms in a given hotel go for the
    same rate.  For people who book multiple nights, the second night
    goes for 95 percent of the first night, the third night goes for 95
    percent of the second night, and so on.  Write a program that
    enables you to specify the hotel and the numbers of nights and gives
    you the total charge.  Use a menu that enables you to continue
    entering data until you choose to quit.

    Program:
    /* hotel.c -- calculates hotel bills */
    #include <stdio.h>

    #define LAST_CHOICE 'e'

    #define RATEA  50.00
    #define RATEB  55.00
    #define RATEC  80.00
    #define RATED 100.00

    #define DISCOUNT 0.95

    int get_choice(void);
    double get_rate(int choice);
    int get_nights(void);
    double calc_bill(double rate, int nights);

    int main(void)
    {
      int choice, nights;
      double rate, bill;

      printf("This program calculates hotel bills.\n");

      while ((choice = get_choice()) != LAST_CHOICE)
      {
        rate = get_rate(choice);
        if ((nights = get_nights()) < 0)
          break;
        bill = calc_bill(rate, nights);
        printf("bill = $%.2lf\n", bill);
      }
      return 0;
    }

    int get_choice(void)
    {
      int choice;

      /* prompt user for menu choice */
      printf("\nPlease enter one of the following:\n");
      printf("a) Fairfield Arms\n");
      printf("b) Hotel Olympic\n");
      printf("c) Chertworthy Plaza\n");
      printf("d) The Stockton\n");
      printf("e) Quit\n");

      /* get valid menu choice loop */
      while (1)
      {
        /* get menu choice and handle EOF */
        if ((choice = getchar()) == EOF)
        {
          choice = LAST_CHOICE;
          break;
        }

        /* clear input buffer */
        if (choice != '\n')
          while (getchar() != '\n');

        /* handle valid menu choice */
        if (choice >= 'a' && choice <= LAST_CHOICE)
          break;

        /* handle invalid menu choice */
        printf("Error: invalid menu choice.  Please retry.\n");
      }

      /* return valid menu choice */
      return choice;
    }

    double get_rate(int choice)
    {
      double rate;

      /* using menu choice, find hotel rate */
      switch (choice)
      {
        case 'a':
          rate = RATEA;
          break;
        case 'b':
          rate = RATEB;
          break;
        case 'c':
          rate = RATEC;
          break;
        case 'd':
          rate = RATED;
          break;
      }
      return rate;
    }

    int get_nights(void)
    {
      int status, nights;

      /* prompt user for number of nights */
      printf("Please enter number of nights.\n");

      /* get valid number of nights loop */
      while (1)
      {
        /* get number of nights and handle quit case */
        if ((status = scanf("%d", &nights)) == EOF)
        {
          nights = -1;
          break;
        }

        /* clear input buffer */
        while (getchar() != '\n');

        /* handle valid number of nights */
        if (status == 1 && nights >= 0)
          break;

        /* handle invalid number of nights */
        printf("Error: invalid number of nights.  Please retry.\n");
      }

      /* return valid number of nights */
      return nights;
    }

    double calc_bill(double rate, int nights)
    {
      int i;
      double bill;

      /* using hotel rate and number of nights, calculate bill */
      bill = 0.0;
      for (i = 1; i <= nights; i++)
      {
        bill += rate;
        rate *= DISCOUNT;
      }
      return bill;
    }

    Screen:
    Output: This program calculates hotel bills.
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  a
    Output: Please enter number of nights.
    Input:  1
    Output: bill = $50.00
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  b
    Output: Please enter number of nights.
    Input:  2
    Output: bill = $107.25
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  c
    Output: Please enter number of nights.
    Input:  3
    Output: bill = $228.20
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  d
    Output: Please enter number of nights.
    Input:  4
    Output: bill = $370.99
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  abc
    Output: Please enter number of nights.
    Input:  1
    Output: bill = $50.00
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  xyz
    Output: Error: invalid menu choice.  Please retry.
    Input:  a
    Output: Please enter number of nights.
    Input:  2abc
    Output: bill = $97.50
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  a
    Output: Please enter number of nights.
    Input:  -1
    Output: Error: invalid number of nights.  Please retry.
    Input:  xyz
    Output: Error: invalid number of nights.  Please retry.
    Input:  3
    Output: bill = $142.63
    Output:
    Output: Please enter one of the following:
    Output: a) Fairfield Arms
    Output: b) Hotel Olympic
    Output: c) Chertworthy Plaza
    Output: d) The Stockton
    Output: e) Quit
    Input:  e

17. Example 9.15
    ------------
    Problem:
    The 1988 United States Federal Estimated Tax Schedule is the
    simplest in recent times.  It has four categories, and each category
    has two rates.  Here is a summary (dollar amounts are taxable
    income):
        Category           Tax
        Single             15% of first $17,850 plus 28% of excess
        Head of household  15% of first $23,900 plus 28% of excess
        Married, joint     15% of first $29,750 plus 28% of excess
        Married, separate  15% of first $14,875 plus 28% of excess
    For instance, a single wage earner with a taxable income of $20,000
    dollars owes 0.15x$17,850+0.28x($20,000-$17,850).  Write a program
    that lets the user specify the tax category and the taxable income
    and then calculates the tax.  Use a loop so that the user can enter
    several tax cases.

    Program:
    /* tax.c -- calculates income tax */
    #include <stdio.h>

    #define LAST_CHOICE 5

    #define LIMIT1 17850.0
    #define LIMIT2 23900.0
    #define LIMIT3 29750.0
    #define LIMIT4 14875.0

    #define RATE1 0.15
    #define RATE2 0.28

    int get_choice(void);
    double get_limit(int choice);
    double get_income(void);
    double calc_tax(double limit, double income);

    int main(void)
    {
      int choice;
      double limit, income, tax;

      printf("This program calculates income tax.\n");

      while ((choice = get_choice()) != LAST_CHOICE)
      {
        limit = get_limit(choice);
        if ((income = get_income()) < 0.0)
          break;
        tax = calc_tax(limit, income);
        printf("tax = $%.2lf\n", tax);
      }
      return 0;
    }

    int get_choice(void)
    {
      int status, choice;

      /* prompt user for menu choice */
      printf("\nPlease enter one of the following:\n");
      printf("1) Single\n");
      printf("2) Head of household\n");
      printf("3) Married, joint\n");
      printf("4) Married, separate\n");
      printf("5) Quit\n");

      /* get valid menu choice loop */
      while (1)
      {
        /* get menu choice and handle EOF */
        if ((status = scanf("%d", &choice)) == EOF)
        {
          choice = LAST_CHOICE;
          break;
        }

        /* clear input buffer */
        while (getchar() != '\n');

        /* handle valid menu choice */
        if (status == 1 && choice >= 1 && choice <= LAST_CHOICE)
          break;

        /* handle invalid menu choice */
        printf("Error: invalid menu choice.  Please retry.\n");
      }

      /* return valid menu choice */
      return choice;
    }

    double get_limit(int choice)
    {
      double limit;

      /* using menu choice find, limit for rates */
      switch (choice)
      {
        case 1:
          limit = LIMIT1;
          break;
        case 2:
          limit = LIMIT2;
          break;
        case 3:
          limit = LIMIT3;
          break;
        case 4:
          limit = LIMIT4;
          break;
      }
      return limit;
    }

    double get_income(void)
    {
      int status;
      double income;

      /* prompt user for income */
      printf("Please enter income.\n");

      /* get valid income loop */
      while (1)
      {
        /* get income and handle quit case */
        if ((status = scanf("%lf", &income)) == EOF)
        {
          income = -1.0;
          break;
        }

        /* clear input buffer */
        while (getchar() != '\n');

        /* handle valid income */
        if (status == 1 && income >= 0.0)
          break;

        /* handle invalid income */
        printf("Error: invalid income.  Please retry.\n");
      }

      /* return valid income */
      return income;
    }

    double calc_tax(double limit, double income)
    {
      double income1, income2, tax;

      /* using limit and income, find income at rate1 and income at
         rate2 */
      if (income <= limit)
      {
        income1 = income;
        income2 = 0.0;
      } 
      else
      {
        income1 = limit;
        income2 = income - limit;
      }

      /* using income1, rate1, income2, and rate2, calculate tax */
      tax = income1*RATE1 + income2*RATE2;
      return tax;
    }

    Screen:
    Output: This program calculates income tax.
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  1
    Output: Please enter income.
    Input:  15000
    Output: tax = $2250.00
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  2
    Output: Please enter income.
    Input:  27500
    Output: tax = $4593.00
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  3
    Output: Please enter income.
    Input:  25000
    Output: tax = $3750.00
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  4
    Output: Please enter income.
    Input:  17500
    Output: tax = $2966.25
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  1abc
    Output: Please enter income.
    Input:  15000
    Output: tax = $2250.00
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  6
    Output: Error: invalid menu choice.  Please retry.
    Input:  xyz
    Output: Error: invalid menu choice.  Please retry.
    Input:  1
    Output: Please enter income.
    Input:  16000abc
    Output: tax = $2400.00
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  1
    Output: Please enter income.
    Input:  -1000
    Output: Error: invalid income.  Please retry.
    Input:  xyz
    Output: Error: invalid income.  Please retry.
    Input:  17000
    Output: tax = $2550.00
    Output:
    Output: Please enter one of the following:
    Output: 1) Single
    Output: 2) Head of household
    Output: 3) Married, joint
    Output: 4) Married, separate
    Output: 5) Quit
    Input:  5

18. Recursion
    ---------
    Definition:
    Recursion: when a function calls itself.

    Note:
    (1) A recursive function must include a conditional test to
        terminate the recursion.
    (2) Each level of recursion has its own variables.
    (3) Each function call is balanced with a return.  When program flow
        reaches the return at the end of the last recursion level,
        control passes to the previous recursion level.
    (4) Statements in a recursive function that precede the recursive
        call are executed in the same order that the functions are
        called.
    (5) Statements in a recursive function that follow the recursive
        call are executed in the opposite order from which the functions
        are called.
    (6) Although each level of recursion has its own set of variables,
        the code itself is not duplicated.
   
19. Example 9.16
    ------------
    Program:
    /* recur.c -- shows recursion */
    #include <stdio.h>
    void up_and_down(int n);
    int main(void)
    {
      up_and_down(1);
      return 0;
    }

    void up_and_down(int n)
    {
      printf("Level %d\n", n);
      if (n < 4)
        up_and_down(n+1);
      printf("LEVEL %d\n", n);
    }

    Output:
    Level 1
    Level 2
    Level 3
    Level 4
    LEVEL 4
    LEVEL 3
    LEVEL 2
    LEVEL 1

20. Example 9.17
    ------------
    Problem:
    Write and test a function that calculates the factorial of a number.
    Use recursion.

    Algorithm:
    (1) n! = n x (n-1)!
    (2) 0! = 1

    Program:
    /* factor2.c -- calculates factorial of a number */
    #include <stdio.h>
    long fact(int n);
    int main(void)
    {
      int num;

      printf("This program calculates the factorial of a number.\n");
      while (1)
      {
        printf("\nPlease enter a positive integer less than 16.\n");
        printf("Type q to quit.\n");     
        if (scanf("%d", &num) != 1)
          break;
        if (num < 0 || num > 15)
        {
          printf("Error: 0 <= integer <= 15.\n");
          continue;
        }
        printf("%d! = %ld\n", num, fact(num));
      }
      return 0;
    }

    long fact(int n)
    {
      long ans;

      if (n > 0)
        ans = n * fact(n-1);
      else
        ans = 1;
      return ans;
    }

    Screen:
    Output: This program calculates the factorial of a number.
    Output:
    Output: Please enter a positive integer less than 16.
    Output: Type q to quit.
    Input:  4
    Output: 4! = 24
    Output:
    Output: Please enter a positive integer less than 16.
    Ouput:  Type q to quit.
    Input:  6
    Output: 6! = 720
    Output:
    Output: Please enter a positive integer less than 16.
    Output: Type q to quit.
    Input:  q

21. Example 9.18
    ------------
    Problem:
    Write and test a function that prints an integer in binary.

    Algorithm:
    Let n be a positive number.
    The final binary digit is n%2.
    The next binary digit is (n/2)%2.
    The next binary digit is ((n/2)/2)%2.
    ...

    Program:
    /* binary.c -- prints integer in binary */
    #include <stdio.h>
    void to_binary(int n);
    int main(void)
    {
      int num;

      printf("This program prints an integer in binary.\n");
      while (1)
      {
        printf("\nPlease enter a positive integer.  Type q to quit.\n");
        if (scanf("%d", &num) != 1)
          break;
        if (num < 0)
        {
          printf("Error: integer must be positive.\n");
          continue;
        }
        to_binary(num);
        putchar('\n');
      }
      return 0;
    }

    void to_binary(int n)
    {
      int r;

      r = n % 2;
      if (n >= 2)
        to_binary(n / 2);
      printf("%d", r);
    }

    Screen:
    Output: This program prints an integer in binary.
    Output:
    Output: Please enter a positive integer.  Type q to quit.
    Input:  11
    Output: 1011
    Output:
    Output: Please enter a positive integer.  Type q to quit.
    Input:  25
    Output: 11001
    Output:
    Output: Please enter a positive integer.  Type q to quit.
    Input:  q

22. Introduction to Pointers
    ------------------------
    (1) Memory -- Addresses
        (a) * Declaration
            Declaration:
            type *ptr;
            Meaning:
            ptr contains the address of a value of the given type.
        (b) & Operator
            Code:
            ...&name...
            Meaning:
            Address of name.
        (c) * Operator
            Code:
            type *ptr;
            ...*ptr...
            Meaning:
            Go to ptr and get the address, and then go to the address
            and get/store the value.
            
    (2) Diagram -- Arrows
        (a) * Declaration
            Declaration:
            type *ptr;
            Meaning:
            ptr contains an arrow to a value of the given type.
        (b) & Operator
            Code:
            ...&name...
            Meaning:
            Arrow to name.
        (c) * Operator
            Code:
            type *ptr;
            ...*ptr...
            Meaning:
            Go to ptr and get the arrow, and then follow the arrow and
            get/store the value.

23. Example 9.19
    ------------
    Program:
    /* ptr.c -- shows pointers */
    #include <stdio.h>
    int main(void)
    {
      int num1, num2;

      /* * declaration
         (1) addresses
             ptr contains the address of a value of type int
         (2) arrows
             ptr contains an arrow to a value of type int */
      int *ptr;

      num1 = 1;
      printf("num1 = %d\n", num1);

      /* & operator
         (1) addresses
             address of num
         (2) arrows
             arrow to num */
      ptr = &num1;
      printf("ptr = %p\n", ptr);

      /* * operator - get
         (1) addresses
             go to ptr and get the address, and then go to the address
             and get the value
         (2) arrows
             go to ptr and get the arrow, and then follow the arrow and
             get the value */
      num2 = *ptr;
      printf("num2 = %d\n", num2);

      /* * operator - store
         (1) addresses
             go to ptr and get the address, and then go to the address
             and store the value
         (2) arrows
             go to ptr and get the arrow, and then follow the arrow and
             store the value */
      *ptr = 5;
      printf("num1 = %d\n", num1);
      return 0;
    }

    Output:
    num1 = 1
    ptr = 0100
    num2 = 1
    num1 = 5
     
24. Using Pointers to Communicate Between Functions
    -----------------------------------------------
    To return more than one value from a function we need to use
    pointers.

    (1) Function Needs a Value
        (a) Call:
            function_name(...call_expression...)
              /* passes value of call_expression */
        (b) Function Definition:
            return_type function_name(...type func_variable...)
            {
              ...
              /* func_variable - get/store value at func_variable */
              ...
            }

    (2) Function Needs to Alter Variables in the Calling Function
        (a) Call:
            function_name(...&call_variable...)
              /* passes address of call_variable */
        (b) Function Definition:
            type function_name(...type *func_variable...)
            {
              ...
              /* *func_variable - get/store value at call_variable */
              ...
            }

25. Example 9.20
    ------------
    Program #1:
    /* value.c -- shows passing a value */
    #include <stdio.h>
    void func(int num);
    int main(void)
    {
      int a = 1;

      printf("main(): a = %d\n", a);
      func(a);
      printf("main(): a = %d\n", a);
      return 0;
    }

    void func(int num)
    {
      printf("func(): num = %d\n", num);
      num = 5;
      printf("func(): num = %d\n", num);
    }

    Output #1:
    main(): a = 1
    func(): num = 1
    func(): num = 5
    main(): a = 1

    Program #2:
    /* address.c -- shows passing an address */
    #include <stdio.h>
    void func(int *ptr);
    int main(void)
    {
      int a = 1;

      printf("main(): &a = %p, a = %d\n", &a, a);
      func(&a);
      printf("main(): &a = %p, a = %d\n", &a, a);
      return 0;
    }

    void func(int *ptr)
    {
      printf("func(): ptr = %p, *ptr = %d\n", ptr, *ptr);
      *ptr = 5;
      printf("func(): ptr = %p, *ptr = %d\n", ptr, *ptr);
    }

    Output #2:
    main(): &a = 0100, a = 1
    func(): ptr = 0100, *ptr = 1
    func(): ptr = 0100, *ptr = 5
    main(): &a = 0100, a = 5

26. Example 9.21
    ------------
    Problem:
    Write and test a function that converts seconds to minutes and
    seconds.

    Program:
    /* seconds.c -- converts seconds to minutes and seconds */
    #include <stdio.h>
    #define SEC_PER_MIN 60
    void calc_sec(int num, int *ptr_min, int *ptr_sec);
    int main(void)
    {
      int num, min, sec;

      printf("This program converts seconds to minutes and seconds.\n");
      while (1)
      {
        printf("\nPlease enter number of seconds.  Type q to quit.\n");
        if (scanf("%d", &num) != 1)
          break;
        calc_sec(num, &min, &sec);
        printf("%d seconds is %d minutes and %d seconds.\n", num, min,
          sec);
      }
      return 0;
    }

    void calc_sec(int num, int *ptr_min, int *ptr_sec)
    {
      int min, sec;

      min = num/SEC_PER_MIN;
      sec = num%SEC_PER_MIN;
      *ptr_min = min;
      *ptr_sec = sec;
    }

    Function #2:
    void calc_sec(int num, int *ptr_min, int *ptr_sec)
    {
      *ptr_min = num/SEC_PER_MIN;
      *ptr_sec = num%SEC_PER_MIN;
    }

    Screen:
    Output: This program converts seconds to minutes and seconds.
    Output:
    Output: Please enter number of seconds.  Type q to quit.
    Input:  150
    Output: 150 seconds is 2 minutes and 30 seconds.
    Output:
    Output: Please enter number of seconds.  Type q to quit.
    Input:  250
    Output: 250 seconds is 4 minutes and 10 seconds.
    Output:
    Output: Please enter number of seconds.  Type q to quit.
    Input:  q

27. Example 9.22
    ------------
    Problem:
    Write and test a function that swaps the values of two integer
    variables.

    Program:
    /* swap.c -- swaps the values of two integer variables */
    #include <stdio.h>
    void swap(int *ptr_num1, int *ptr_num2);
    int main(void)
    {
      int num1, num2;

      printf("This program swaps the values of two variables.\n");
      while (1)
      {
        printf("\nPlease enter two integers.  Type q to quit.\n");
        if (scanf("%d %d", &num1, &num2) != 2)
          break;
        printf("Original values: num1 = %d, num2 = %d\n", num1, num2);
        swap(&num1, &num2);
        printf("Swapped values:  num1 = %d, num2 = %d\n", num1, num2);
      }
      return 0;
    }

    void swap(int *ptr_num1, int *ptr_num2)
    {
      int num1, num2, temp;

      num1 = *ptr_num1;
      num2 = *ptr_num2;
      temp = num1;
      num1 = num2;
      num2 = temp;
      *ptr_num1 = num1;
      *ptr_num2 = num2;
    }

    Function #2:
    void swap(int *ptr_num1, int *ptr_num2)
    {
      int temp;

      temp = *ptr_num1;
      *ptr_num1 = *ptr_num2;
      *ptr_num2 = temp;
    }

    Screen:
    Output: This program swaps the values of two variables.
    Output:
    Output: Please enter two integers.  Type q to quit.
    Input:  1 3
    Output: Original values: num1 = 1, num2 = 3
    Output: Swapped values:  num1 = 3, num2 = 1
    Output:
    Output: Please enter two integers.  Type q to quit.
    Input:  7 5
    Output: Original values: num1 = 7, num2 = 5
    Output: Swapped values:  num1 = 5, num2 = 7
    Output:
    Output: Please enter two integers.  Type q to quit.
    Input:  q

28. Example 9.23
    ------------
    Problem:
    Write a program that calculates the circumference and area of a
    circle.

    Program:
    /* circle.c -- calculates the circumference and area of a
                   circle */
    #include <stdio.h>

    #define PI 3.14159

    int get_radius(double *ptr_radius);
    void calc_circle(double radius, double *ptr_circum,
      double *ptr_area);
    void print_circle(double radius, double circum, double area);

    int main(void)
    {
      double radius, circum, area;

      printf("This program calculates the circumference and area\n");
      printf("of a circle.\n");
      while (get_radius(&radius))
      {
        calc_circle(radius, &circum, &area);
        print_circle(radius, circum, area);
      }
      return 0;
    }

    int get_radius(double *ptr_radius)
    {
      int status, ret_val;

      printf("\nPlease enter the radius.  Type EOF to quit.\n");
      while (1)
      {
        if ((status = scanf("%lf", ptr_radius)) == EOF)
        {
          ret_val = 0;
          break;
        }
        while (getchar() != '\n');
        if (status == 1 && *ptr_radius >= 0.0)
        {
          ret_val = 1;
          break;
        }
        printf("Error: invalid input.  Please retry.\n");
      }
      return ret_val;
    }

    void calc_circle(double radius, double *ptr_circum,
      double *ptr_area)
    {
      *ptr_circum = 2.0 * PI * radius;
      *ptr_area = PI * radius * radius;
    }

    void print_circle(double radius, double circum, double area)
    {
      printf("%-6s  %-13s  %-6s\n", "Radius", "Circumference", "Area");
      printf("------  -------------  ------\n");
      printf("%6.2lf  %13.2lf  %6.2lf\n", radius, circum, area);
    }

    Screen:
    Output: This program calculates the circumference and area
    Output: of a circle.
    Output:
    Output: Please enter the radius.  Type EOF to quit.
    Input:  2.5
    Output: Radius  Circumference  Area  
    Output: ------  -------------  ------
    Output:   2.50          15.71   19.63
    Output:
    Output: Please enter the radius.  Type EOF to quit.
    Input:  3.5 inches
    Output: Radius  Circumference  Area  
    Output: ------  -------------  ------
    Output:   3.50          21.99   38.48
    Output:
    Output: Please enter the radius.  Type EOF to quit.
    Input:  -4.5
    Output: Error: invalid input.  Please retry.
    Input:  four point five
    Output: Error: invalid input.  Please retry.
    Input:  4.5
    Output: Radius  Circumference  Area  
    Output: ------  -------------  ------
    Output:   4.50          28.27   63.62
    Output:
    Output: Please enter the radius.  Type EOF to quit.
    Input:  [Ctrl-Z] (Unix: [Ctrl-D])
 



4



