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


 1. While Loop
    ----------
    Form:
    (1) while (expression)
          statement;
    (2) while (expression)
        {
          statement(s)
        }

    Meaning:
                |
       -------->|
       |        V
       |       / \  zero
       |      /exp\----------
       |      \   / (false) |
       |       \ /          |
       |        | nonzero   |
       |        V (true)    |
       |  ----------------  |
       |  | statement(s) |  |
       |  ----------------  |
       |        |           |
       ----------           |
                -------------
                |
                V

    Note:
    (1) (a) If there is no opening brace ({) immediately after
            while (expression) then the body of the loop runs up to the
            first semicolon (;).
        (b) If there is an opening brace ({) immediately after
            while (expression) then the body of the loop runs up to the
            matching closing brace (}).
    (2) The while statement is an entry-condition loop, which means that
        the decision to go through one more pass of the loop is made
        before the loop is traversed.  Thus, the body of the loop may
        never be executed.

 2. Example 6.1
    -----------
    Problem:
    Write a program to echo an integer.

    Program #1:
    /* while1.c -- echos an integer */
    #include <stdio.h>
    int main(void)
    {
      int num;

      /* braces are optional when the body of the loop is one
         statement */
      printf("This program echos an integer.\n");
      printf("Please enter an integer.  Type q to quit.\n");
      while (scanf("%d", &num) == 1)
        printf("num = %d\n", num);
      printf("**********\n");
      return 0;
    }

    Screen #1:
    Output: This program echos an integer.
    Output: Please enter an integer.  Type q to quit.
    Input:  3
    Output: num = 3
    Input:  5
    Output: num = 5
    Input:  7
    Output: num = 7
    Input:  q
    Output: **********

    Program #2:
    /* while2.c -- echos an integer */
    #include <stdio.h>
    int main(void)
    {
      int num;

      /* braces are required when the body of the loop is more than one
         statement */
      printf("This program echos an integer.\n");
      printf("Please enter an integer.  Type q to quit.\n");
      while (scanf("%d", &num) == 1)
      {
        printf("num = %d\n", num);
        printf("**********\n");
      }
      return 0;
    }

    Screen #2:
    Output: This program echos an integer.
    Output: Please enter an integer.  Type q to quit.
    Input:  3
    Output: num = 3
    Output: **********
    Input:  5
    Output: num = 5
    Output: **********
    Input:  7
    Output: num = 7
    Output: **********
    Input:  q

    Program #3:
    /* while3.c -- echos an integer */
    #include <stdio.h>
    int main(void)
    {
      int num;

      /*** error ***/
      /* semicolon after while (...) -- body of loop is empty */
      printf("This program echos an integer.\n");
      printf("Please enter an integer.  Type q to quit.\n");
      while (scanf("%d", &num) == 1);
      {
        printf("num = %d\n", num);
        printf("**********\n");
      }
      return 0;
    }

    Screen #3:
    Output: This program echos an integer.
    Output: Please enter an integer.  Type q to quit.
    Input:  3
    Input:  5
    Input:  7
    Input:  q
    Output: num = 7
    Output: **********

 3. Example 6.2
    -----------
    Problem:
    Write a program that asks the user to enter the radius of a circle.
    Calculate the circumference and area of the circle.  Then print the
    results.  Have the program loop through input values until the user
    enters nonnumeric input.

    Program:
    /* circle.c -- calculates the circumference and area of a circle */
    #include <stdio.h>
    #define PI 3.14159
    int main(void)
    {
      double radius, circum, area;

      printf("This program calculates the circumference and area\n");
      printf("of a circle.\n");

      /* get radius from user */
      printf("\nPlease enter the radius.  Type q to quit.\n");
      while (scanf("%lf", &radius) == 1)
      {
        /* calculate circumference and area */
        circum = 2.0 * PI * radius;
        area = PI * radius * radius;

        /* print results */     
        printf("radius = %.2lf\n", radius);
        printf("circumference = %.2lf\n", circum);
        printf("area = %.2lf\n", area);

        printf("\nPlease enter the radius.  Type q to quit.\n");
      }

      return 0;
    }

    Screen:
    Output: This program calculates the circumference and area
    Output: of a circle.
    Output:
    Output: Please enter the radius.  Type q to quit.
    Input:  2.5
    Output: radius = 2.50
    Output: circumference = 15.71
    Output: area = 19.63
    Output:
    Output: Please enter the radius.  Type q to quit.
    Input:  3.2
    Output: radius = 3.20
    Output: circumference = 20.11
    Output: area = 32.17
    Output:
    Output: Please enter the radius.  Type q to quit.
    Input:  q

 4. Example 6.3
    -----------
    Problem:
    Write a program that asks the user to enter the price per night at a
    hotel and the number of nights stayed at the hotel.  Calculate the
    hotel bill.  Then print the results.  Have the program loop through
    input values until the user enters nonnumeric input.

    Program:
    /* hotel.c -- calculates a hotel bill */
    #include <stdio.h>
    int main(void)
    {
      int nights;
      double price, bill;

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

      /* get price per night and number of nights from user */
      printf("\nPlease enter the price per night and number of "
          "nights.\n");
      printf("Type q to quit.\n");
      while (scanf("%lf %d", &price, &nights) == 2)
      {
        /* calculate hotel bill */
        bill = price * nights;

        /* print results */
        printf("%-6s  %-6s  %-6s\n", "Price", "Nights", "Bill");
        printf("------  ------  ------\n");
        printf("%6.2lf  %6d  %6.2lf\n", price, nights, bill);

        printf("\nPlease enter the price per night and number of "
            "nights.\n");
        printf("Type q to quit.\n");
      }

      return 0;
    }

    Screen:
    Output: This program calculates a hotel bill.
    Output:
    Output: Please enter the price per night and number of nights.
    Output: Type q to quit.
    Input:  75.50 3
    Output: Price   Nights  Bill  
    Output: ------  ------  ------
    Output:  75.50       3  226.50
    Output:
    Output: Please enter the price per night and number of nights.
    Output: Type q to quit.
    Input:  125.00 5
    Output: Price   Nights  Bill  
    Output: ------  ------  ------
    Output: 125.00       5  625.00
    Output:
    Output: Please enter the price per night and number of nights.
    Output: Type q to quit.
    Input:  q

 5. Example 6.4
    -----------
    Problem:
    Write a program that averages a list of integers.

    Program:
    /* average.c -- averages a list of integers */
    #include <stdio.h>
    int main(void)
    {
      int num, count, sum;

      printf("This program averages a list of integers.\n");
      printf("Please enter a list of integers.  Type q to quit.\n");
      count = sum = 0;
      while (scanf("%d", &num) == 1)
      {
        sum += num;
        count++;
      }
      printf("average = %.2lf\n", (double)sum/(double)count);
      return 0;
    }     

    Screen:
    Output: This program averages a list of integers.
    Output: Please enter a list of integers.  Type q to quit.
    Input:  2 5 9 q
    Output: average = 5.33

 6. For Loop
    --------
    Form:
    (1) for (initialize expression; test expression; update expression)
          statement;
    (2) for (initialize expression; test expression; update expression)
        {
          statement(s)
        }

    Meaning:
                    |
                    V
        -------------------------
        | initialize expression |
        -------------------------
                    |
       |----------->|
       |            V
       |           / \
       |          /   \  zero
       |         /test \-------------
       |         \ exp / (false)    |
       |          \   /             |
       |           \ /              |
       |            |               |
       |            | nonzero       |
       |            V (true)        |
       |      ----------------      |
       |      | statement(s) |      |
       |      ----------------      |
       |            |               |
       |            V               |
       |  ---------------------     |
       |  | update expression |     |
       |  ---------------------     |
       |             |              |
       ---------------              |
                     ----------------
                     |
                     V

    Note:
    (1) (a) If there is no opening brace ({) immediately after
            for (expressions) then the body of the loop runs up to the
            first semicolon (;).
        (b) If there is an opening brace ({) immediately after
            for (expressions) then the body of the loop runs up to the
            matching closing brace (}).
    (2) The for statement is an entry-condition loop, which means that
        the decision to go through one more pass of the loop is made
        before the loop is traversed.  Thus, the body of the loop may
        never be executed.
    (3) An empty test is considered to be true.
    (4) It is usually NOT a good idea to alter the parameters of the
        loop expression within the loop.

 7. Example 6.5
    -----------
    Program #1:
    /* for1.c -- for loop */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i;

      /* braces are optional when the body of the loop is one
         statement */
      for (i = 1; i <= LIMIT; i++)
        printf("i = %d\n", i);
      printf("**********\n");
      return 0;
    }

    Output #1:
    i = 1
    i = 2
    i = 3
    **********

    Program #2:
    /* for2.c -- for loop */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i;

      /* braces are required when the body of the loop is more than one
         statement */
      for (i = 1; i <= LIMIT; i++)
      {
        printf("i = %d\n", i);
        printf("**********\n");
      }
      return 0;
    }

    Output #2:
    i = 1
    **********
    i = 2
    **********
    i = 3
    **********

    Program #3:
    /* for3.c -- for loop */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i;

      /*** error ***/
      /* semicolon after for (...) -- body of loop is empty */
      for (i = 1; i <= LIMIT; i++);
      {
        printf("i = %d\n", i);
        printf("**********\n");
      }
      return 0;
    }

    Output #3:
    i = 4
    **********

 8. Example 6.6
    -----------
    Program #1:
    /* for4.c -- for loop */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i;

      /* starts at 1 and counts up by 1 */
      for (i = 1; i <= LIMIT; i++)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Output #1:
    i = 1
    i = 2
    i = 3
    last i = 4

    Program #2:
    /* for5.c -- for loop */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i;

      /* starts at 0 and counts up by 1 */
      for (i = 0; i < LIMIT; i++)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Output #2:
    i = 0
    i = 1
    i = 2
    last i = 3

    Program #3:
    /* for6.c -- for loop */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i;

      /* counts down by 1 to 1 */
      for (i = LIMIT; i >= 1; i--)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Output #3:
    i = 3
    i = 2
    i = 1
    last i = 0

    Program #4:
    /* for7.c -- for loop */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i;

      /* counts down by 1 to 0 */
      for (i = LIMIT-1; i >= 0; i--)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Output #4:
    i = 2
    i = 1
    i = 0
    last i = -1

    Program #5:
    /* for8.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      char ch;

      /* counts by characters */
      for (ch = 'a'; ch <= 'z'; ch++)
        printf("ch = '%c', ASCII code = %d\n", ch, ch);
      return 0;
    }

    Output #5:
    ch = 'a', ASCII code = 97
    ch = 'b', ASCII code = 98
    ch = 'c', ASCII code = 99
    ch = 'd', ASCII code = 100
      ...               ...
    ch = 'z', ASCII code = 122

    Program #6:
    /* for9.c -- for loop */
    #include <stdio.h>
    #define LIMIT 20 
    int main(void)
    {
      int pow2;

      /* you can use any legal expression for the update expression */
      for (pow2 = 2; pow2 <= LIMIT; pow2 *= 2)
        printf("pow2 = %d\n", pow2);
      return 0;
    }

    Output #6:
    pow2 = 2
    pow2 = 4
    pow2 = 8
    pow2 = 16

    Program #7:
    /* for10.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int num, limit;

      /* you can have an empty expression */
      printf("Please enter a lower and upper limit.\n");
      scanf("%d %d", &num, &limit);
      for (; num <= limit; num++)
        printf("num = %d\n", num);
      return 0;
    }

    Screen #7:
    Output: Please enter a lower and upper limit.
    Input:  2 5
    Output: num = 2
    Output: num = 3
    Output: num = 4
    Output: num = 5

    Program #8:
    /* for11.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int num, count;

      /* you can test some condition other than the number of
         iterations */
      /* you can have an empty body */
      printf("Please enter some integers.  Type q to quit.\n");
      for (count = 0; scanf("%d", &num) == 1; count++);
      printf("count = %d\n", count);
      return 0;
    }

    Screen #8:
    Output: Please enter some integers.  Type q to quit.
    Input:  2 5 9 q
    Output: count = 3

 9. Example 6.7
    -----------
    Correct Program:
    /* for12.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int i;

      for (i = -3; i < 0; i++)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Correct Output:
    i = -3
    i = -2
    i = -1
    last i = 0

    Error Program #1:
    /* for13.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int i;

      /*** error ***/
      /* test reversed -- body of loop never executed */
      for (i = -3; i >= 0; i++)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Error Output #1:
    last i = -3

    Error Program #2:
    /* for14.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int i;

      /*** error ***/
      /* incrementing instead of decrementing -- infinite loop */
      for (i = -3; i < 0; i--)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Error Output #2:
    i = -3
    i = -4
    i = -5
    i = -6
     ...

    Error Program #3:
    /* for15.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int i;

      /*** error ***/
      /* i never changes -- infinite loop */
      for (i = -3; i < 0; i)
        printf("i = %d\n", i);
      printf("last i = %d\n", i);
      return 0;
    }

    Error Output #3:
    i = -3
    i = -3
    i = -3
    i = -3
     ...

10. Example 6.8
    -----------
    Error Program:
    /* for16.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int i, n = 3;

      /*** error ***/
      /* n changes -- infinite loop */
      for (i = 1; i <= n; i++)
      {
        printf("i = %d, n = %d\n", i, n);
        n++;
      }
      return 0;
    }

    Error Output:
    i = 1, n = 3
    i = 2, n = 4
    i = 3, n = 5
    i = 4, n = 6
     ...    ...

    Correct Program:
    /* for17.c -- for loop */
    #include <stdio.h>
    int main(void)
    {
      int i, n = 3, limit;

      /* n changes, but limit does not change */
      limit = n;
      for (i = 1; i <= limit; i++)
      {
        printf("i = %d, n = %d, limit = %d\n", i, n, limit);
        n++;
      }
      return 0;
    }

    Correct Output:
    i = 1, n = 3, limit = 3
    i = 2, n = 4, limit = 3
    i = 3, n = 5, limit = 3

11. Example 6.9
    -----------
    Problem:
    Write a program that prints a table of squares and cubes.

    Program:
    /* sq_cube.c -- prints a table of squares and cubes */
    #include <stdio.h>
    int main(void)
    {
      int num, limit, square, cube;

      printf("This program prints a table of squares and cubes.\n");
      printf("Please enter an upper limit.\n");
      scanf("%d", &limit);
      printf("%-6s  %-6s  %-6s\n", "Number", "Square", "Cube");
      printf("------  ------  ------\n");
      for (num = 1; num <= limit; num++)
      {
        square = num * num;
        cube = square * num;
        printf("%6d  %6d  %6d\n", num, square, cube);
      }
      return 0;
    }

    Screen:
    Output: This program prints a table of squares and cubes.
    Output: Please enter an upper limit.
    Input:  5
    Output: Number  Square  Cube  
    Output: ------  ------  ------
    Output:      1       1       1
    Output:      2       4       8
    Output:      3       9      27
    Output:      4      16      64
    Output:      5      25     125

12. Comma Operator
    --------------
    Table of Operators
    ------------------
    Comma Operator:
    Operator   Meaning
       ,       Links two expressions into one and guarantees that the
               leftmost expression is evaluated first.  The value of the
               whole expression is the value of the righthand
               expression.

    Note:
    The comma operator is used to include more information in a for loop
    initialize expression and/or update expression.  Do not use the
    comma operator in a for loop test expression because only the value
    of the righthand expression will be used.
    
    Table of Operators in Order of Decreasing Precedence
    ----------------------------------------------------
         Operator                                   Associativity
     (1) ++(postfix) --(postfix) ()                 left to right
     (2) ++(prefix) --(prefix) +(unary) -(unary) !  right to left
         sizeof (type)(all unary)
     (3) * / %                                      left to right
     (4) +(binary) -(binary)                        left to right
     (5) < > <= >=                                  left to right
     (6) == !=                                      left to right
     (7) &&                                         left to right
     (8) ||                                         left to right
     (9) = *= /= %= += -=                           right to left
    (10) ,(comma operator)                          left to right

13. Example 6.10
    ------------
    Program:
    /* comma.c -- comma operator */
    #include <stdio.h>
    #define LIMIT 3
    int main(void)
    {
      int i, j;

      /* the comma operator is used to include more information in a
         for loop initialize expression and/or update expression */
      for (i = 1, j = LIMIT; i <= LIMIT; i++, j--)
        printf("i = %d, j = %d\n", i, j);
      return 0;
    }

    Output:
    i = 1, j = 3
    i = 2, j = 2
    i = 3, j = 1

14. Example 6.11
    ------------
    Problem:
    Write a program that computes the following.
        sum = 1 + 2 + 3 + ...

    Program:
    /* series1.c -- computes 1 + 2 + 3 + ... */
    #include <stdio.h>
    int main(void)
    {
      int i, nterms, sum;

      printf("This program computes the following.\n");
      printf("    sum = 1 + 2 + 3 + ...\n");
      printf("Please enter the number of terms.\n");
      scanf("%d", &nterms);
      for (i = 1, sum = 0; i <= nterms; i++)
        sum += i;
      printf("sum = %d\n", sum);
      return 0;
    }

    Screen:
    Output: This program computes the following.
    Output:     sum = 1 + 2 + 3 + ...
    Output: Please enter the number of terms.
    Input:  4
    Output: sum = 10

15. Example 6.12
    ------------
    Problem:
    Write a program that computes the following.
        product = 1 * 2 * 3 * ...

    Program:
    /* series2.c -- computes 1 * 2 * 3 * ... */
    #include <stdio.h>
    int main(void)
    {
      int i, nterms, prod;

      printf("This program computes the following.\n");
      printf("    product = 1 * 2 * 3 * ...\n");
      printf("Please enter the number of terms.\n");
      scanf("%d", &nterms);
      for (i = 1, prod = 1; i <= nterms; i++)
        prod *= i;
      printf("product = %d\n", prod);
      return 0;
    }

     Screen:
     Output: This program computes the following.
     Output:     product = 1 * 2 * 3 * ...
     Output: Please enter the number of terms.
     Input:  4
     Output: product = 24

16. Example 6.13
    ------------
    Problem:
    Write a program that computes the following.
                    1   1   1
        total = 1 + - + - + - + ...
                    2   3   4

    Program:
    /* series3.c -- computes 1 + 1/2 + 1/3 + 1/4 + ... */
    #include <stdio.h>
    int main(void)
    {
      int i, nterms;
      double total;

      printf("This program computes the following.\n");
      printf("    total = 1 + 1/2 + 1/3 + 1/4 + ...\n");
      printf("Please enter the number of terms.\n");
      scanf("%d", &nterms);
      for (i = 1, total = 0.0; i <= nterms; i++)
        total += 1.0/i;
      printf("total = %lf\n", total);
      return 0;
    }

     Screen:
     Output: This program computes the following.
     Output:      total = 1 + 1/2 + 1/3 + 1/4 + ...
     Output: Please enter the number of terms.
     Input:  4
     Output: total = 2.083333

17. Example 6.14
    ------------
    Problem:
    Write a program that finds how many terms it takes for the
    following series to reach a given limit.
                 0    1    2    3
        total = 2  + 2  + 2  + 2  + ...

    Program:
    /* series4.c -- computes how many terms it takes for the series
                    2**0 + 2**1 + 2**2 + 2**3 + ... to reach a given 
                    limit */
    #include <stdio.h>
    int main(void)
    {
      int i, limit, pow2, total;

      printf("This program computes how many terms it takes for the\n");
      printf("following series to reach a given limit.\n");
      printf("    total = 2**0 + 2**1 + 2**2 + 2**3 + ...\n");
      printf("Please enter a limit.\n");
      scanf("%d", &limit);
      for (i = 0, pow2 = 1, total = 0; total < limit; i++)
      {
        total += pow2;
        pow2 *= 2;
      }
      printf("number of terms = %d, total = %d\n", i, total);
      return 0;
    }

    Screen:
    Output: This program computes how many terms it takes for the
    Output: following series to reach a given limit.
    Output:     total = 2**0 + 2**1 + 2**2 + 2**3 + ...
    Output: Please enter a limit.
    Input:  25
    Output: number of terms = 5, total = 31

18. Do While Loop
    -------------
    Form:
    (1) do
          statement;
        while (expression);
    (2) do
        {
          statement(s)
        }
        while (expression);

    Meaning:
                   |
       ----------->|
       |           V
       |     ----------------
       |     | statement(s) |
       |     ----------------
       |           |
       |           V
       |  nonzero / \
       ----------/exp\
          (true) \   /
                  \ /
                   | zero
                   V (false)

    Note:
    (1) If you attempt to put more than one statement between the
        do and the while without the enclosing braces, the compiler
        will generate an error message at the start of the second
        statement.
    (2) The do-while statement is an exit-condition loop, which means
        that the decision to go through one more pass of the loop is
        made after the loop is traversed.  Thus, the body of the loop
        must be executed at least once.

19. Example 6.15
    ------------
    Program:
    /* dowhile.c -- compare while and do-while loop */
    #include <stdio.h>
    int main(void)
    {
      int num, lower, upper;
       
      printf("Please enter a lower and upper limit.\n");
      scanf("%d %d", &lower, &upper);

      /* while: entry-condition loop */
      /* the body of the loop may never be executed */
      printf("while:\n");
      num = lower;
      while (num <= upper)
      {
        printf("num = %d\n", num);
        num++;
      }
      printf("last num = %d\n", num);

      /* do-while: exit-condition loop */
      /* the body of the loop is always executed at least once */
      printf("do-while:\n");
      num = lower;
      do
      {
        printf("num = %d\n", num);
        num++;
      }
      while (num <= upper);
      printf("last num = %d\n", num);
      return 0;
    }

    Screen #1:
    Output: Please enter a lower and upper limit.
    Input:  1 3
    Output: while:
    Output: num = 1
    Output: num = 2
    Output: num = 3
    Output: last num = 4
    Output: do-while:
    Output: num = 1
    Output: num = 2
    Output: num = 3
    Output: last num = 4

    Screen #2:
    Output: Please enter a lower and upper limit.
    Input:  4 3
    Output: while:
    Output: last num = 4
    Output: do-while:
    Output: num = 4
    Output: last num = 5

20. Nested Loops
    ------------
    A nested loop is a loop that is inside another loop.

21. Example 6.16
    ------------
    Program:
    /* nested1.c -- nested loops */
    #include <stdio.h>
    int main(void)
    {
      int num, lower, upper;

      printf("Please enter a lower and upper limit.  Type q to "
        "quit.\n");
      while (scanf("%d %d", &lower, &upper) == 2)
      {
        for (num = lower; num <= upper; num++)
          printf("num = %d\n", num);
        printf("\nPlease enter a lower and upper limit.  Type q to "
          "quit.\n");
      }
      return 0;
    }

    Screen:
    Output: Please enter a lower and upper limit.  Type q to quit.
    Input:  1 3
    Output: num = 1
    Output: num = 2
    Output: num = 3
    Output:
    Output: Please enter a lower and upper limit.  Type q to quit.
    Input:  6 9
    Output: num = 6
    Output: num = 7
    Output: num = 8
    Output: num = 9
    Output:
    Output: Please enter a lower and upper limit.  Type q to quit.
    Input:  q

22. Example 6.17
    ------------
    Program:
    /* nested2.c -- nested loops */
    #include <stdio.h>
    #define LIMIT1 2
    #define LIMIT2 3
    int main(void)
    {
      int i, j;

      printf("start outer loop\n");
      for (i = 0; i < LIMIT1; i++)
      {
         printf("start inner loop\n");
         for (j = 0; j < LIMIT2; j++)
           printf("i = %d, j = %d\n", i, j);
         printf("finish inner loop\n");
      }
      printf("finish outer loop\n");
      return 0;
    }

    Output:
    start outer loop
    start inner loop
    i = 0, j = 0
    i = 0, j = 1
    i = 0, j = 2
    finish inner loop
    start inner loop
    i = 1, j = 0
    i = 1, j = 1
    i = 1, j = 2
    finish inner loop
    finish outer loop

23. Example 6.18
    ------------
    Problem:
    Write a program that prints a character in a triangle.

    Program:
    /* pattern1.c -- prints a character in a triangle */
    #include <stdio.h>
    int main(void)
    {
      char ch;
      int i, j, n;

      printf("This program prints a character in a triangle.\n");
      printf("Please enter a character and a number of lines.\n");
      scanf("%c %d", &ch, &n);
      for (i = 1; i <= n; i++)
      {
        for (j = 1; j <= i; j++)
          printf("%c", ch);
        printf("\n");
      }
      return 0;
    }

    Screen:
    Output: This program prints a character in a triangle.
    Output: Please enter a character and a number of lines.
    Input:  * 5
    Output: *
    Output: **
    Output: ***
    Output: ****
    Output: *****

24. Example 6.19
    ------------
    Problem:
    Write a program that prints the following pattern.
    A
    ABA
    ABCBA
     ...

    Program:
    /* pattern2.c -- prints the alphabet in a triangle */
    #include <stdio.h>
    int main(void)
    {
      char ch, last;
      int i, n;

      printf("This program prints the alphabet in a triangle.\n");
      printf("Please enter a number of lines.\n");
      scanf("%d", &n);
      for (i = 1; i <= n; i++)
      {
        last = 'A' + (i-1);
        for (ch = 'A'; ch <= last; ch++)
          printf("%c", ch);
        for (ch = last-1; ch >= 'A'; ch--)
          printf("%c", ch);
        printf("\n");
      }
      return 0;
    }

    Screen:
    Output: This program prints the alphabet in a triangle.
    Output: Please enter a number of lines.
    Input:  4
    Output: A
    Output: ABA
    Output: ABCBA
    Output: ABCDCBA

25. Arrays
    ------
    Form:
    (1) Declaration
        type name[size];
            where type = the type of each element in the array
                  name = the name of the array
                  size = the number of elements in the array
    (2) Executable Code
        ... name[pos] ...
            where name = the name of the array
                  pos  = the position in the array
          
    Meaning:
    (1) Declaration
                     Memory
                     -------
        name[0]      |     |
                     -------
        name[1]      |     |
                     -------
        name[2]      |     |
                     -------
        ...          | ... |
                     -------
        name[size-1] |     |
                     -------
    (2) Executable Code
                     Memory
        ...             ...
                     ---------
        name[pos]    | value |
                     ---------
        ...             ...
        (a) If name[pos] appears in an expression it means get the value
            stored at position pos in the name array.
        (b) If name[pos] appears on the left-side of an assignment
            statement it means store the value at position pos in the
            name array.

    Note:
    (1) Array size must be an int or long constant known at compile
        time.
    (2) (a) Array positions must be type int or long.
        (b) Array positions can be a constant, variable, or expression.
        (c) Array positions start at 0 and go to size-1.
    (3) A string is a char array in which the null character, '\0', is
        used to mark the end of the string.  If you pass a character
        array that is not terminated with a '\0' to a standard library
        string function such as printf() with %s or strlen(), the
        function will not behave properly.
    (4) C does not do run-time array bounds checking.
        (a) If you access name[pos], where pos is out of bounds you will
            get a random value.
        (b) If you store at name[pos], where pos is out of bounds one of
            three things will happen.
            1) You may get lucky and not overwrite anything important.
            2) You may overwrite another variable's value.
            3) You may overwrite code in which case your program will
               probably hang.

26. Example 6.20
    ------------
    Program #1:
    /* arr1.c -- arrays */
    #include <stdio.h>
    #define SIZE 5
    int main(void)
    {
      double arr[SIZE];

      /* array positions start at 0 and go to size-1 */
      arr[0] = 1.5;
      arr[1] = 3.5;
      arr[2] = 5.5;
      arr[3] = 7.5;
      arr[4] = 9.5;
      printf("arr = %.2lf %.2lf %.2lf %.2lf %.2lf\n", arr[0], arr[1],
        arr[2], arr[3], arr[4]);
      return 0;
    }

    Trace #1:
           Memory
           -------
    arr[0] | 1.5 |
           -------
    arr[1] | 3.5 |
           -------
    arr[2] | 5.5 |
           -------
    arr[3] | 7.5 |
           -------
    arr[4] | 9.5 |
           -------

    Output #1:
    arr = 1.50 3.50 5.50 7.50 9.50

    Program #2:
    /* arr2.c -- strings */
    #include <stdio.h>
    #define LENGTH 2
    int main(void)
    {
      char str[LENGTH+1];

      /* a string is a char array in which the null character, '\0', is
         used to mark the end of the string */
      str[0] = 'a';
      str[1] = 'b';
      str[2] = '\0';
      printf("str = \"%s\"\n", str);
      return 0;
    }

    Trace #2:
            Memory
           --------
    str[0] |  'a' |
           --------
    str[1] |  'b' |
           --------
    str[2] | '\0' |
           --------

    Output #2:
    str = "ab"

    Program #3:
    /* arr3.c -- arrays */
    #include <stdio.h>
    int main(void)
    {
      /*** error ***/
      /* the size of an array must be an int or long constant known at
         compile time */
      int n;
      int arr[n];
      /* sample.c(8) : error C2057: expected constant expression */
      /* sample.c(8) : error C2133: 'arr' : unknown size */

      printf("Please enter the number of elements.\n");
      scanf("%d", &n);
      ...
      return 0;
    }

    Comment #3:
    Compiling this program generates the error messages shown above.

    Program #4:
    /* arr4.c -- arrays */
    #include <stdio.h>
    #include <string.h>
    #define LENGTH 2
    int main(void)
    {
      char str1[LENGTH+1];
      char str2[LENGTH];

      /*** error ***/
      /* if you pass a character array that is not terminated with a
         '\0' to a standard library string function such as printf()
         with %s or strlen(), the function will not behave properly */
      str1[0] = 'a';
      str1[1] = 'b';
      str1[2] = '\0';
      str2[0] = 'c';
      str2[1] = 'd';
      printf("str1 = \"%s\", len1 = %d\n", str1, strlen(str1));
      printf("str2 = \"%s\", len2 = %d\n", str2, strlen(str2));
      return 0;
    }

    Output #4:    
    str1 = "ab", len1 = 2
    str2 = "cdab", len2 = 4

    Program #5:
    /* arr5.c -- arrays */
    #include <stdio.h>
    #define SIZE 4
    int main(void)
    {
      int i;
      int arr[SIZE];

      /*** error ***/
      /* C does not do run-time array bounds checking */
      arr[0] = 1;
      arr[1] = 3;
      arr[2] = 5;
      arr[3] = 7;

      /* if you access name[pos], where pos is out of bounds you will
         get a random value */
      i = 100;
      printf("arr[%d] = %d\n", i, arr[i]);
      return 0;
    }

    Output #5:
    arr[100] = 17234

    Program #6:
    /* arr6.c -- arrays */
    #include <stdio.h>
    #define LENGTH 3
    int main(void)
    {
      char str[LENGTH+1];
      int i;

      /*** error ***/
      /* C does not do run-time array bounds checking */
      str[0] = 'a';
      str[1] = 'b';
      str[2] = 'c';
      str[3] = '\0';
      printf("str = \"%s\"\n", str);

      /* you may get lucky and not overwrite anything important */
      i = 5;
      str[i] = 'x';
      printf("str = \"%s\"\n", str);
      return 0;
    }

    Trace #6:
            Memory
           --------
    str[0] |  'a' |
           --------
    str[1] |  'b' |
           --------
    str[2] |  'c' |
           --------
    str[3] | '\0' |
           --------
           |      |
           --------
           |      |  /* overwritten by 'x' */
           --------

    Output #6:
    str = "abc"
    str = "abc"

    Program #7:
    /* arr7.c -- arrays */
    #include <stdio.h>
    #define LENGTH 3
    int main(void)
    {
      char str1[LENGTH+1];
      char str2[LENGTH+1];
      int i;

      /*** error ***/
      /* C does not do run-time array bounds checking */
      str1[0] = 'a';
      str1[1] = 'b';
      str1[2] = 'c';
      str1[3] = '\0';
      str2[0] = 'd';
      str2[1] = 'e';
      str2[2] = 'f';
      str2[3] = '\0';
      printf("str1 = \"%s\", str2 = \"%s\"\n", str1, str2);

      /* you may overwrite another variable's value */
      i = 5;
      str2[i] = 'x';
      printf("str1 = \"%s\", str2 = \"%s\"\n", str1, str2);
      return 0;
    }

    Trace #7:
             Memory
            --------
    str2[0] |  'd' |
            --------
    str2[1] |  'e' |
            --------
    str2[2] |  'f' |
            --------
    str2[3] | '\0' |
            --------
            |      |
            --------
            |      |  /* overwritten by 'x' */
            --------

    Output #7:
    str1 = "abc", str2 = "def"
    str1 = "axc", str2 = "def"

    Program #8:
    /* arr8.c -- arrays */
    #include <stdio.h>
    #define SIZE 5
    int main(void)
    {
      int i;
      int arr[SIZE];

      /*** error ***/
      /* C does not do run-time array bounds checking */
      /* you may overwrite code in which case your program will probably
         hang */
      for (i = 0; i < 100; i++)
        arr[i] = 0;
      return 0;      
    }

    Trace #8:
            Memory
            ------
    arr[0]  |  0 |
            ------
    arr[1]  |  0 |
            ------
    arr[2]  |  0 |
            ------
    arr[3]  |  0 |
            ------
    arr[4]  |  0 |
            ------
            |    |  /* overwritten by 0 */
            ------
             ...            ...

    Comment #8:
    Program hangs.
    
27. Example 6.21
    ------------
    Program #1:
    /* arr9.c -- arrays */
    #include <stdio.h>
    #define SIZE 4
    int main(void)
    {
      int i;
      int arr[SIZE];

      /* read array */
      printf("Please enter %d integers.\n", SIZE);
      for (i = 0; i < SIZE; i++)
        scanf("%d", &arr[i]);

      /* print array in original order */
      printf("Original Order\n");
      for (i = 0; i < SIZE; i++)
        printf("arr[%d] = %d\n", i, arr[i]);

      /* print array in reverse order */
      printf("Reverse Order\n");
      for (i = SIZE-1; i >= 0; i--)
        printf("arr[%d] = %d\n", i, arr[i]);
      return 0;
    }

    Screen #1:
    Output: Please enter 4 integers.
    Input:  1 3 5 7
    Output: Original Order
    Output: arr[0] = 1
    Output: arr[1] = 3
    Output: arr[2] = 5
    Output: arr[3] = 7
    Output: Reverse Order
    Output: arr[3] = 7
    Output: arr[2] = 5
    Output: arr[1] = 3
    Output: arr[0] = 1
    
    Program #2:
    /* arr10.c -- arrays */
    #include <stdio.h>
    #define SIZE 4
    int main(void)
    {
      int i;
      int arr1[SIZE], arr2[SIZE];

      /* assign odd numbers to first array */
      for (i = 0; i < SIZE; i++)
        arr1[i] = 2*i+1;

      /* print first array */
      printf("First Array\n");
      for (i = 0; i < SIZE; i++)
        printf("arr1[%d] = %d\n", i, arr1[i]);

      /* assign powers of 2 to second array */
      arr2[0] = 1;
      for (i = 1; i < SIZE; i++)
        arr2[i] = arr2[i-1]*2;

      /* print second array */
      printf("Second Array\n");
      for (i = 0; i < SIZE; i++)
        printf("arr2[%d] = %d\n", i, arr2[i]);
      return 0;
    }

    Output #2:
    First Array
    arr1[0] = 1
    arr1[1] = 3
    arr1[2] = 5
    arr1[3] = 7
    Second Array
    arr2[0] = 1
    arr2[1] = 2
    arr2[2] = 4
    arr2[3] = 8

    Program #3:
    /* arr11.c -- arrays */
    #include <stdio.h>
    #define SIZE 4
    int main(void)
    {
      int i;
      int arr1[SIZE], arr2[SIZE];

      arr1[0] = 11;
      arr1[1] = 13;
      arr1[2] = 10;
      arr1[3] = 12;

      arr2[0] = 2;
      arr2[1] = 0;
      arr2[2] = 3;
      arr2[3] = 1;

      /* print first array in sorted order using positions in second
         array */
      for (i = 0; i < SIZE; i++)
        printf("arr1[arr2[%d]] = arr1[%d] = %d\n", i, arr2[i],
          arr1[arr2[i]]);
      return 0;
    }

    Output #3:
    arr1[arr2[0]] = arr1[2] = 10
    arr1[arr2[1]] = arr1[0] = 11
    arr1[arr2[2]] = arr1[3] = 12
    arr1[arr2[3]] = arr1[1] = 13

28. Example 6.22
    ------------
    Problem:
    Write a program that stores the squares of the integers in one array
    and the cubes of the integers in a second array.  Then have the
    program print out the arrays.

    Program:
    /* sq_cube.c -- creates and prints array of squares and array of
                    cubes */
    #include <stdio.h>
    #define LIMIT 10
    int main(void)
    {
      int i, num;
      int squares[LIMIT];
      int cubes[LIMIT];

      printf("This program creates and prints an array of squares\n");
      printf("and an array of cubes.\n");

      /* store squares and cubes in arrays */
      for (i = 0, num = 1; i < LIMIT; i++, num++)
      {
        squares[i] = num * num;
        cubes[i] = squares[i] * num;
      }

      /* print arrays */
      printf("%-6s  %-6s  %-6s\n", "Number", "Square", "Cube");
      printf("------  ------  ------\n");
      for (i = 0, num = 1; i < LIMIT; i++, num++)
        printf("%6d  %6d  %6d\n", num, squares[i], cubes[i]);
      return 0;
    }

    Output:
    This program creates and prints an array of squares
    and an array of cubes.
    Number  Square  Cube  
    ------  ------  ------
         1       1       1
         2       4       8
         3       9      27
         4      16      64
         5      25     125
         6      36     216
         7      49     343
         8      64     512
         9      81     729
        10     100    1000

29. Example 6.23
    ------------
    Problem:
    Write a program that reads in a lowercase word and converts it to
    uppercase.

    Program:
    /* low_up.c -- converts lowercase word to uppercase */
    #include <stdio.h>
    #include <string.h>
    int main(void)
    {
      int i, n;
      char word[81];

      printf("This program converts a lowercase word to uppercase.\n");

      /* read in a lowercase word */
      printf("Please enter a lowercase word.\n");
      scanf("%s", word);

      /* convert lowercase word to uppercase */
      n = strlen(word);
      for (i = 0; i < n; i++)
        word[i] = 'A' + (word[i] - 'a');

      /* print uppercase word */
      printf("uppercase word = \"%s\"\n", word);
      return 0;
    }

    Screen:
    Output: This program converts a lowercase word to uppercase.
    Output: Please enter a lowercase word.
    Input:  cat
    Output: uppercase word = "CAT"

30. Example 6.24
    ------------
    Problem:
    Write a program that reads test scores and calculates their average.

    Program:
    /* scores.c -- reads test scores and calculates their average */
    #include <stdio.h>
    #define MAX 10
    int main(void)
    {
      int i, nscores, sum;
      int scores[MAX];

      printf("This program reads test scores and calculates their "
        "average.\n");

      /* read scores */
      /* (1) when reading into an array you need to check the following:
             (a) stay within array bounds
             (b) let user quit early
         (2) applying logical operator order of evaluation rules to the
             for loop test expression:
             (a) if i is 10, i<10 is false so the computer won't try to
                 store in arr[10] which is outside the array bounds
             (b) if you reverse the order of the tests and i is 10, the
                 computer will try to store in arr[10] before it
                 realizes that i<10 is false */
      printf("Please enter up to %d test scores.  Type q to quit.\n",
        MAX);
      for (i = 0; i < MAX && scanf("%d", &scores[i]) == 1; i++);
      nscores = i;

      /* print scores */
      printf("Test Scores\n");
      for (i = 0; i < nscores; i++)
        printf("%d ", scores[i]);
      printf("\n");

      /* calculate and print average */
      for (i = 0, sum = 0; i < nscores; i++)
        sum += scores[i];
      printf("average = %.2lf\n", (double)sum/(double)nscores);
      return 0;
    }

    Screen:
    Output: This program reads test scores and calculates their average.
    Output: Please enter up to 10 test scores.  Type q to quit.
    Input:  76 85 62 q
    Output: Test Scores
    Output: 76 85 62 
    Output: average = 74.33

31. Example 6.25
    ------------
    Problem:
    Write a program that deletes the number at a given position in an
    array.

    Program:
    /* delete.c -- deletes the number at a given position in an array */
    #include <stdio.h>
    #define MAX 10
    int main(void)
    {
      int i, n, pos;
      double arr[MAX];

      printf("This program deletes the number at a given position "
        "in an array.\n");

      /* assign values to variables */
      arr[0] = 1.5;
      arr[1] = 3.5;
      arr[2] = 5.5;
      arr[3] = 7.5;
      arr[4] = 9.5;
      n = 5;
      pos = 2;

      /* print original array */
      printf("Original Array\n");
      for (i = 0; i < n; i++)
        printf("arr[%d] = %.2lf\n", i, arr[i]);
      printf("Delete position counting from 0 = %d\n", pos);

      /* delete number at given position by moving the rest of the
         numbers in the array up one position */     
      for (i = pos+1; i < n; i++)
        arr[i-1] = arr[i];
      n--;

      /* print array after deletion */
      printf("Array After Delete\n");
      for (i = 0; i < n; i++)
        printf("arr[%d] = %.2lf\n", i, arr[i]);
      return 0;
    }

    Output:
    This program deletes the number at a given position in an array.
    Original Array
    arr[0] = 1.50
    arr[1] = 3.50
    arr[2] = 5.50
    arr[3] = 7.50
    arr[4] = 9.50
    Delete position counting from 0 = 2
    Array After Delete
    arr[0] = 1.50
    arr[1] = 3.50
    arr[2] = 7.50
    arr[3] = 9.50
 



4



