In-Class Practice

Function Walkthrough


What is the output of the following program:

 // Functions
 //
 #define TIMES 3
 #define SETS  4
 #define COLOR 1
 #include <stdio.h>
 int control(int color, int times, int nsets);

 int main(void)
 {
         int color, result;

         color  = COLOR;
         result = control(color, TIMES, SETS);
         printf("%d\n", result);
         printf("%d\n", color);

         return 0;
 }

 int control(int color, int times, int nsets)
 { 
         int sec, set;

         if (color < 0 || color > 2)
                 color = 0;
         sec = 0;
         set = 0;
         printf("%d,%d,%d\n", color, times, nsets);
         while ( set < nsets ) {
                 switch ( color ) {
                 case 0:
                         printf("G ");
                         sec = sec + 1;
                         break;
                 case 1:
                         printf("Y ");
                         sec = sec + times;
                         break;
                 case 2:
                         printf("R ");
                         sec = sec + 1;
                         break;
                 default:
                         printf("O ");
                         sec = sec + 1;
                 }
                 if (color != 0 || sec % times == 0)
                         printf("Wt ");
                 else
                         printf("Wk ");
                 if (sec % times == 0) {
                         printf("(%d,%d)\n", sec, set);
                         set = set + 1;
                         if (color == 2) {
                                 sec = 0;
                                 color = 0;
                         } else {
                                 color = color + 1;
                         }
                 }
         }

         return color;
 }

Prepare the table:

  • show the name of each function
  • show the type of each local variable
  • show the name of each local variable
  • optionally, select a unique address for each local variable

Exclude printf(), since there is no need to walkthrough the internal logic of printf().

int control ( int color, int times, int nsets )int main ( )
intintintintintintint
colortimesnsetssecsetcolorresult
             


       
       
       
       
       
       
       
       
       
       
       
       
       
       
       


Output:




























   Printer Friendly Version of this Page print this page     Top  Go Back to the Top of this Page



  Designed by Chris Szalwinski   Copying From This Site   

Creative Commons License