Sum the integers from 1 to a user-specified number

#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;//ww w. ja va 2 s . c o m printf("\nTotal of the first %u numbers is %llu\n", count, sum); return 0; }

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;

- for Statement
- Draw a box using for loop
- for Loop Control Options
- Use Nested for Loops to draw box
- Use Nested for Loops to sum successive integer sequences
- Nesting for loops