C - Sum the integers from 1 to a user-specified number

Description

Sum the integers from 1 to a user-specified number

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 1 to count
      for(unsigned int i = 1 ; i <= count ; ++i)
        sum += i;/*  w ww .jav a  2  s .c  om*/

      printf("\nTotal of the first %u numbers is %llu\n", count, sum);
      return 0;
}

Result

We start by declaring and initializing two variables that you'll need during the calculation:

unsigned long long sum = 0LL;            // Stores the sum of the integers
unsigned int count = 0;                   // The number of integers to be summed

We use sum to hold the final result of your calculations.

We declare it as type unsigned long long to allow the maximum total.

The variable count stores the integer that's entered as the number of integers to be summed.

To read user input:

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

If the user enters 4, for instance, the program will compute the sum of 1, 2, 3, and 4.

the sum is calculated in the following loop:

for(unsigned int i = 1 ; i <= count ; ++i)
      sum += i;

Related Example