L-33 MCS 260 Mon 5 Nov 2001

Answers to Review Questions on Chapters 5 to 8

Below are the questions followed by a possible solution. In some cases a main program is included for testing.

  1. Give a definition of the following function
             int hash ( char c );
             /* returns 0 for c equal to a,b,c,..,or g,
                        1                h,i,j,..,or n,
                        2                o,p,q,..,or t,
                        3                u,v,w,..,or z   */
    

    Answer:

    /* L-33 MCS 260 Mon 5 Nov 2001 : review question 1 */
    
    int hash ( char c );
    /* returns 0 for c equal to a,b,c,..,or g,
               1                h,i,j,..,or n,
               2                o,p,q,..,or t,
               3                u,v,w,..,or z   */
    
    #include<stdio.h>
    
    int main ( void )
    {
       char c;
    
       for (;;)
       {
          printf("Give character ( 0 to stop ) : ");
          if ((c = getchar()) == '0') break;
          printf("Value of hash function : %d\n", hash(c));
          c = getchar(); /* skip new line symbol */
       }
    
       return 0;
    }
    
    int hash ( char c )
    {
       if (( 'a' <= c ) && ( c <= 'g' )) return 0;
       if (( 'h' <= c ) && ( c <= 'n' )) return 1;
       if (( 'o' <= c ) && ( c <= 't' )) return 2;
       if (( 'u' <= c ) && ( c <= 'z' )) return 3;
    }
    

  2. Write a graceful print that avoids control characters, using the prototype
            void graceful_print ( int c );
            /* prints c if it is not a control character,
               otherwise nothing happens */
    

    Answer:

          #include<ctype.h>
    
          void graceful_print ( int c )
          {
             if (!iscntrl(c)) putchar(c);
          }
    

  3. Write a program that reads in a sequence of characters and that prints out the same sequence, except with all newline symbols replaced by tabs.

    Answer:

    /* L-33 MCS 260 Mon 5 Nov 2001 : review question 2
    
       Write a program that reads in a sequence of characters
       and that prints out the same sequence, except with
       all newline symbols replaced by tabs.                 */
    
    #include<stdio.h>
    
    int main ( void )
    {
       int c;
    
       while ((c = getchar()) != EOF)
          if (c == '\n')
             putchar('\t');
          else
             putchar(c);
    
       return 0;
    }
    

  4. Give a definition of the following function
            int bitcnt ( int n );
            /* returns the number of ones in the binary representation
               of the integer number n */
    

    Answer:

    /* L-33 MCS 260 Mon 5 Nov 2001 : review question 4   */
    
    int bitcnt ( int n );
    /* returns the number of ones in the binary representation
       of the integer number n */
    
    #include<stdio.h>
    
    int main ( void )
    {
       int n;
    
       for (;;)
       {
          printf("Give a positive integer ( <=0 to stop ) : ");
          scanf("%d", &n);
          if (n <= 0) break;
          printf("Number of ones in bit representation of %d : %d\n",
                 n, bitcnt(n));
       }
    
       return 0;
    }
    
    int bitcnt ( int n )
    {
       int cnt = 0;
       int work;
    
       for (work = n; work > 0; work /= 2)
          cnt += (work % 2);
    
       return cnt;
    }
    

  5. Write a program that reads two integers, makes their quotient in double floating-point arithmetic and prints this quotient with 15 decimal places.

    Answer:

    /* L-33 MCS 260 Mon 5 Nov 2001 : review question 5
    
       Write a program that reads two integers, makes their
       quotient in double floating-point arithmetic and prints
       this quotient with 15 decimal places.                   */
    
    #include<stdio.h>
    
    int main ( void )
    {
       int a, b;
       double quotient;
    
       scanf("%d %d", &a, &b);
       quotient = ((double) a)/((double) b);
    
       printf("%d/%d = %.15lf\n", a, b, quotient);
    
       return 0;
    }
    

  6. Define an enumeration type speed that can take the following values :
           { walking, slow, normal, fast, racing }
    

    1. Adjust your definition of speed so that the five values correspond to the respective integers (expressing mph) : 5, 20, 45, 60, 90.

    2. Write input/output routines for the type speed.
      The input routine scans the corresponding integer value defined above. Use call-by-reference.
      The output routine writes a meaningful string for each speed level.

    3. Give a definition of the following function
        float distance ( speed s, float t );
        /* returns miles traveled when driven at the given speed s for t hours */
      

    Answer:

    /* L-33 MCS 260 Mon 5 Nov 2001 : review question 6  */
    
    enum speed { walking=5, slow=20, normal=45, fast=60, racing=90 };
    typedef   enum speed   speed;
    
    void read ( speed *s );
    /* reads a speed level into s */
    
    void alternative_read ( speed *s );
    /* reads a speed level into s in an alternative way */
    
    void write ( speed s );
    /* writes the speed level from s */
    
    float distance ( speed s, float t );
    /* returns miles traveled when driven at the given speed s for t hours */
    
    #include<stdio.h>
    
    int main ( void )
    {
       float t;
       speed s;
    
       alternative_read(&s);   /* or read(&s); */
       write(s);
    
       printf("Give time (in hours) : "); scanf("%f", &t);
       printf("Distance traveled in %.2f hours : %.2f miles.\n",
               t, distance(s,t));
    
       return 0;
    }
    
    void read ( speed *s )
    {
       int level;
    
       printf("Give 5, 20, 45, 60, or 90 : ");
       scanf("%d", &level);
    
       switch(level)
       {
          case  5: *s = walking; break;
          case 20: *s = slow;    break;
          case 45: *s = normal;  break;
          case 60: *s = fast;    break;
          case 90: *s = racing;  break;
          default: printf("illegal speed level\n");
       }
    }
    
    void alternative_read ( speed *s )
    {
       int level;
    
       printf("Give 5, 20, 45, 60, or 90 : ");
       scanf("%d", &level);
    
       switch(level)
       {
          case  5: 
          case 20: 
          case 45: 
          case 60:
          case 90: *s = (speed) level; break;
          default: printf("illegal speed level\n");
       }
    }
    
    void write ( speed s )
    {
       printf("Your speed is %d mph,", s);
       switch(s)
       {
          case walking: printf(" at walking pace.\n"); break;
          case slow:    printf(" going slow.\n");      break;
          case normal:  printf(" moving normally.\n"); break;
          case fast:    printf(" going fast.\n");      break;
          case racing:  printf(" at racing pace.\n");
       }
    }
    
    float distance ( speed s, float t )
    {
       return s*t;
    }
    

  7. Consider the following program
         #include<stdio.h>
         int main(void)
         {                             e               p
            float e = 2.718;           +----------+    +-----+
            float *p = &e;             | 2.718000 |<---|- &e |
                                       +----------+    +-----+
            printf("%f", *p);
            *p = 2.718281;             e               p
            printf("%f", *p);          +----------+    +-----+
                                       | 2.718281 |<---|- &e |
            return 0;                  +----------+    +-----+
         }
    
    Draw a diagram to illustrate the relations between p and e. Indicate the values of those variables before and after executing the last assignment. What does the program print? 2.7180002.718281

  8. Consider the following program
         int OddAdd ( int *s, int n );                variables
                                                ---------------------------------
         int main(void)                           in main |     in OddAdd
         {                                      =================================
            int sum = 0;                before:  sum      |
                                                   +---+  |
            OddAdd(&sum,3);                        | 0 |  |
                                                   +---+  |
            return 0;                                     |
         }                              during:  sum      | s         n     a
                                                   +---+  | +-------+ +---+ +---+
         int OddAdd ( int *s, int n )              | 0 |<---|- &sum | | 3 | | 3 |
         {                                         +---+  | +-------+ +---+ +---+
            int a = (n % 2 == 1)? n : 0;                  |                  
                                         after:  sum      | 
            *s += a;                               +---+  |
         }                                         | 3 |  |
                                                   +---+  |
    
    Make a diagram representing all variables in main and OddAdd. Illustrate with the diagram what happens before, during, and after the call of OddAdd(&sum).

Please note the policy on skipping exams:

If an exam is missed, then greater weight will be placed on the final exam, especially on the material covered on the missing exam.

What this means is that if you decide not to take one midterm exam, your final exam will be weighted for one hundred points more.

What it does NOT mean is that you can drop the score of a midterm exam. If you take the midterm, then your score counts. So, please be prepared when you show up for the exam.