Exercise 2-10 - CBD p. 71

Solution index                   Textual C program


#include <stdio.h>

int main(void) {  
  
  int exponent = 0, powerOfTwo = 1; 
  int status = 0;

  printf("++exponent\n");
  while (++exponent <= 10) {
    printf("%5d", powerOfTwo *= 2);
  }

  exponent = 0;
  powerOfTwo = 1; 

  printf("\n\nexponent++\n");
  while (exponent++ <= 10) {
    printf("%5d", powerOfTwo *= 2);
  }

  return status;    

} /* END OF MAIN */


We write two versions of the while loop. The first corresponds to the program text on page 58 in CBD. The second while loop is slightly changed, as suggested in the exercise page 71. We discuss the differences between the two versions below.
 

  int exponent = 0, powerOfTwo = 1; 
  int status = 0;
Declaration of variables.
 

  printf("++exponent\n");
  while (++exponent <= 10) {
    printf("%5d", powerOfTwo *= 2);
  }
The while loop is executed as long as the value of exponent is less than or equal to 10. Each time the loop is executed, powerOfTwo is set equal to the value it had at the beginning of the loop, multiplied by two. The value being printed in printf is 2 * powerOfTwo. Thus the first value printed in the loop is 2. ++exponent increments the exponent variable before the value of exponent is compared with 10. It means that the first comparion is 1 <= 10. powerOfTwo is assigned a new value each time printf() is called in the loop. %5d means that 5 spaces are reserved for the value to be printed. At the end of the loop, the condition is checked again; since exponent starts with the value 0 and is pre-incremented before its value is compared to 10, the loop will be executed 10 times.
 

  exponent = 0;
  powerOfTwo = 1; 
Reset the variables, such that we can start all over.
 

  printf("\n\nexponent++\n");
  while (exponent++ <= 10) {
    printf("%5d", powerOfTwo *= 2);
The following loop is a copy of the one above, except that this time exponent is post-incremented, i.e., its value is incremented after it is compared to 10. The first comparion done in the while loop is 0 <= 10. The loop is thus executed 11 times.
 

  return status;    
Terminate program.
 

The output of the program is the following:
++exponent
    2    4    8   16   32   64  128  256  512 1024

exponent++
    2    4    8   16   32   64  128  256  512 1024 2048
 


Generated: Wednesday, March 29, 2006, 12:33:15
This program dissection page is generated from an XML-in-LAML source file