L-15 MCS 260 Mon 24 Sep 2001

Answers to review Questions on Chapters 1 to 4

  1. Consider the statements below. What is printed?
           int n = 13;
           printf("%x", n);
    
    Answer := d.

  2. What does this program print?
         #include <stdio.h>
    
         int main(void)
         {
           int i = 4;
           int j = 5;
    
           while (i--) if (i % 2)
           while (j--) printf("%d\n",j);
           else j = i; return 0;
         }
    
    Make a table with three columns: step number in while loop, value for i and value for j.

    Answer: first we reformat the program with proper intendations :

         #include <stdio.h>
    
         int main(void)
         {
           int i = 4;
           int j = 5;
    
           while (i--) 
              if (i % 2)
                 while (j--) printf("%d\n",j);
              else j = i;
    
           return 0;
         }
    
    Even more explicitly, the program reads like
         #include <stdio.h>
    
         int main(void)
         {
           int i = 4;
           int j = 5;
    
           while (i > 0)
           {
              i = i-1;
              if (i % 2 > 0)
                 while (j > 0)
                 {
                    j = j-1;
                    printf("%d\n",j);
                 }
              else
                 j = i; 
           }
           return 0;
         }
    
    Now we understand the program better, we make the table with values for i and j :
      -----------------------------
      | step  |  i  |  j  | print |
      -----------------------------
      |   0   |  4  |  5  |   --  |
      |   1   |  3  |  4  |   4   |
      |       |     |  3  |   3   |
      |       |     |  2  |   2   |
      |       |     |  1  |   1   |
      |       |     |  0  |   0   |
      |   2   |  2  |  2  |   --  |
      |   3   |  1  |  1  |   1   |
      |   4   |     |  0  |   0   |
      |   5   |  0  |     |       |
      -----------------------------
    

  3. For some int n, write a loop to compute the sum of the first n numbers. Write this loop, once using a while, once with a do, and finally once with a for. What kind of loop is most appropriate for this exercise? Explain why.

    Answer with a while :

         int i = 1;
         int s = 0;
         while (i <= n) s += i++;
    
    Answer with a do :
         int i = 0;   /* note the difference, n may be zero */
         int s = 0;
         do
         {
            s += i++;
         }
         while (i <= n);
    
    Answer with a for :
         int s = 0;
         int i;
         for (i = 1; i < n; i++) s += i++;
    
    The for loop is most appropriate because we know in advance how many iterations we will need. A while is most general and a do is useful when we know the loop will be executed at least once and our condition to terminate the loop may depend on those first calculations.

  4. Explain the difference between break and continue Give an example of both.

    Answer: A break is used to leave a loop, while a continue skips all statements in the remained of the loop and continues to evaluate the stop test. Here is an example we have seen in class to compute sum of positive numbers. Negative numbers are ignored and the program leaves when zero is entered.

       int n, sum = 0;
    
       for (;;)             /* infinite loop */
       {
          printf("  Give a number (0 to stop) : ");
    
          if (n < 0)
          {
             printf("Will ignore negative number.\n");
             continue;
          }
          else if (n == 0)
          {
             printf("Will exit the loop now.\n");
             break;
          }
          sum += n;
       }
    
    

  5. Give the definition of a function to compute the step function
             f(x) = 0 if x < 0,
                  = 1 if x >= 0 and x < 1,
                  = 2 if x >= 1 and x < 2,
                  = 3 otherwise
    
    where x and f(x) are of type float. Can you use a switch? Explain why you can or cannot.

    Answer :

           float f ( float x )
           {
              if (x < 0)
                 return 0;
              else if (x < 1)
                 return 1;
              else if (x < 2)
                 return 2;
              else 
                 return 3;
           }
    
    A switch is only appropriate for discrete values, here floats can vary continuously, so we cannot enumerate a list of cases.

  6. Write a basic calculator. The calculator can add, subtract, multiply, and divide two floats at once. The program first reads the two arguments and then the symbol for the operation (+,-,*,\). Before ending, the program prints the result of the calculation. With calc as name of the program, here is a session :
         [jan@galois]% calc
         8.2
         3
         *
         24.6
         [jan@galois]% 
    
    Give first a basic version without any control on input or printing of error messages. Then identify what can go wrong and make the program more robust adding extra checks and more user friendly by printing error messages.

    Answer (basic version) :

    #include<stdio.h>
    
    int main(void)
    {
       float x,y,z;
       char op;
    
       scanf("%f\n", &x);
       scanf("%f\n", &y);
       scanf("%c", &op);
    
       switch(op)
       {
          case '+': z = x+y; break;
          case '-': z = x-y; break;
          case '*': z = x*y; break;
          case '/': z = x/y;
       }
    
       printf("%f\n", z);
    
       return 0;
    }
    

  7. For the roulette game of project two, suppose you had to use the function with prototype :
         int reward ( int outcome, int bet )
         /* returns the tokens gained depending on the values of bet 
            and the outcome; returns 0 if the token used to place the
            bet can be kept, and -1 in all other cases */
    
    Give the main program to implement the project.

    Answer : Note that a high level structure diagram can help you to write the code.

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    
    int reward ( int outcome, int bet );
    
    int main(void)
    {
       int bal,val,bet,rew;
    
       srand(time(NULL));
       printf("Give number of available tokens : "); scanf("%d", &bal);
    
       while (bal > 0)
       {
          printf("Make a bet (<0 to leave) : "); scanf("%d", &bet);
          if (bet < 0) break;
    
          val = rand() % 65;
          rew = reward(val,bet);
          bal += rew;
     
          printf("Outcome is %d,", val);
          if (rew > 0)
             printf(" gained %d token(s),", rew);
          else if (rew == 0)
             printf(" token kept,");
          else
             printf(" token lost,");
          printf(" balance is %d.\n", bal);
       }
    
       bal--;
       printf("Ending balance is %d.", bal);
       if (bal < 0)
          printf("  Pay the gambling fee.\n");
       else
          printf("  Please play again.\n");
    
       return 0;
    }