Exercise 10 - CBD Page 117 - solution with for

Solution index                   Textual C program


#include <stdio.h>

int main(void){

  int n, sum = 0, i;

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

  if (n < 0)
    for(i = 2 * n; i <= n; i++) sum += i;
  else 
    for(i = n; i <= 2 * n; i++) sum += i; 

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

  return 0;
}


This is a solution to exercise 10 on page 117 of C by Dissection using for loops. There is a similar solution with while 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)
    for(i = 2 * n; i <= n; i++) sum += i;
  else 
    for(i = n; i <= 2 * n; i++) 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.
 

    for(i = 2 * n; i <= n; i++) sum += i;
This for loop is used for negative n. We iterate i from 2*n to n; We need to be careful with the expression i <= n, which means that the last value of i summed up is n. While iterating we accumulate the values of i in the variable sum. The for loop has three constituents: i = 2*n initializes i, i <= n controls the iteration, and i++ increments the 'loop variable'.
 

    for(i = n; i <= 2 * n; i++) sum += i; 
This for loop is used for positive n, or if n is zero. For i from n to 2*n i is summed up in the variable sum.
 

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


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