Exercise 10 Page 117 - solution with while

Solution index                   Textual C program


#include <stdio.h>

int main(void){

  int n, sum = 0;

  printf("Enter a positive or negative integer:\n");
  scanf("%d", &n);

  if (n < 0){
    int i = 2 * n;
    while (i <= n) sum += i++;
  }
  else {
    int i = n; 
    while (i <= 2 * n) sum += i++;
  }

  printf("%d \n", sum);

  return 0;
}


This is a solution to exercise 10 on page 117 of C by Dissection using while loops. There is a similar solution with for loops.
 

  printf("Enter a positive or negative integer:\n");
  scanf("%d", &n);
We prompt the user for input with printf, and read a number into the variable n with scanf.
 

  if (n < 0){
    int i = 2 * n;
    while (i <= n) sum += i++;
  }
  else {
    int i = n; 
    while (i <= 2 * n) sum += i++;
  }
The if control structure selects one out of two different 'directions', depending on the sign of n. Notice that we chose the else branch in case n is 0. This is arbitrary; The other branch whould also have been possible without changing the result of the program.
 

    int i = 2 * n;
    while (i <= n) sum += i++;
We first declare i locally. In case n is negative we iterate i from 2*n to n using a while loop. 2*n is smaller than n because n is negative. Notice that the assignment sum += i++ both assigns sum and increments i. The incrementing of i is done after sum is assigned. It is crucical for the termination of the while loop that i is incremented. It can be argued that sum += i++ is too difficult to grasp. Therefore it could be replaced by the two assignments {sum = sum + i; i++}.
 

    int i = n; 
    while (i <= 2 * n) sum += i++;
We first declare i locally. Here we know that n is 0 or positive. The while loop iterates i from n to 2 * n. Notice again that the assignment sum += i++ both assigns sum and increments i.
 

  printf("%d \n", sum);
We print the final sum outside of both the if and the whiles.
 


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