Algorithm


  1. Get n to loop through upto number
  2. Initialize sum = 0;
  3. Loop throw from 1 to n
    1. Inside loop, increment sum with 1 count
  4. Print the sum

Code Examples

#1 Code Example with C Programming

Code - C Programming

#include <stdio.h>
int main()
{
    int number, count, sum = 0;

    printf("Enter the value of n (upto calculate) : ");
    scanf("%d", &number);

    for(count = 1; count  < = number; count++) 
    {
        sum = sum + count; // or sum += count;
    }

    printf("First %d natural numbers sum :  %d", number, sum);

    return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
Enter the value of n (upto calculate) : 20

Output

x
+
cmd
First 20 natural numbers sum : 210
Advertisements

Demonstration


It's knowned also sum of first n numbers.

Just follow the algorithm to understand the concept. It's simple.

Just a basic for loop and inside that loop, increment the sum with count.

Next
Appending into a File in C Programming