/*****************************************
** File: sum1toN.c
** Author: Charles Nicholas
** Date: 2/13/06
**
** This program adds the numbers from 1 to N
** as an example of looping constructs
*****************************************/
#include
#include
int main()
{
int N, i, total;
printf("Sum the numbers from 1 to N\n");
printf("Please enter a value for N:");
scanf("%d",&N);
assert(N >= 1);
/* first, use a while loop */
total = 0;
i = 1;
while (i <= N) {
total += i;
i++;
}
printf("Sum of numbers from 1 to %d is %d\n",N,total);
/* try again using a for loop */
total = 0;
for (i=1; i <= N; i++) {
total += i;
}
printf("Sum of numbers from 1 to %d is %d\n",N,total);
/* try again using a terse version of the for statement */
/* note that we start i at zero instead of 1, which makes */
/* two other minor changes necessary */
for (total = i = 0; i