Exercise 1-14 - CBD p. 38

Solution index                   Textual C program


#include <stdio.h>


int main(void) {  

  int i = 1; 
  int sum = 0;
  int status = 0;

  while (i < 10) {
    sum = sum + i;
    i = i + 1;
    printf("sum = %d, i = %d \n", sum, i);
  }

  return status;    

} /* END OF MAIN */

  int i = 1; 
  int sum = 0;
  int status = 0;
Two integer variables are declared and initialized.
 

  while (i < 10) {
    sum = sum + i;
    i = i + 1;
    printf("sum = %d, i = %d \n", sum, i);
  }
The following loop is executed as long as the value of i is less than 10. Each time the loop is executed, sum is set equal to the value it had at the beginning of the loop, plus the current value of i. i is then incremented by one, and the two values are printed out. At the end of the loop, the condition is checked again; since i starts with the value 1 and is increased by one each time, the loop will be executed 9 times.
 

  return status;    
Terminate program. Output of the program:
sum = 1, i = 2
sum = 3, i = 3
sum = 6, i = 4
sum = 10, i = 5
sum = 15, i = 6
sum = 21, i = 7
sum = 28, i = 8
sum = 36, i = 9
sum = 45, i = 10
 


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