C - Summing integers backward

Introduction

You can change the loop control variable by any amount, positive or negative.

You could sum the first n integers backward as in the following example:

Demo

#include <stdio.h>
int main(void)
{
  unsigned  long long sum = 0LL;// Stores the sum of the integers
  unsigned int count = 0;       // The number of integers to be summed

  // Read the number of integers to be summed
  printf("\nEnter the number of integers you want to sum: ");
  scanf(" %u", &count);

  // Sum integers from count to 1
  for(unsigned int i = count ; i >= 1 ; sum += i--);

  printf("\nTotal of the first %u numbers is %llu\n", count, sum);
  return 0;/*from  w  w  w .  j  a va  2s. co  m*/
}

Result

The loop counter is initialized to count, rather than to 1, and it's decremented on each iteration.

Related Example