C program to find sum of natural numbers from 1 to n

Write a C program to find the sum of all natural numbers between 1 to n using for loop. How to find sum of natural numbers in a given range in C programming. C program to find sum of natural numbers in given range. Logic to find sum of all natural numbers in a given range in C program.

Example

Input

Input upper limit: 10

Output

Sum of natural numbers 1-10: 55

Required knowledge

Basic C programming, For loop

Must read -

Logic to find sum of natural numbers

Below is the step by step descriptive logic to find sum of n natural numbers.

  1. Input upper limit to find sum of natural numbers. Store it in some variable say N.
  2. Initialize another variable, that will hold sum of numbers say sum = 0.
  3. Initialize a loop from 1 to N, incrementing 1 on each iteration. The loop structure should be for(i=1; i<=N; i++).
  4. Inside the loop add previous sum with the current number i. Which is sum = sum + i.
  5. Finally after loop print the value of sum.

Program to find sum of natural numbers

/**
 * C program to find sum of natural numbers between 1 to n
 */

#include <stdio.h>

int main()
{
    int i, n, sum=0;

    /* Input upper limit from user */
    printf("Enter upper limit: ");
    scanf("%d", &n);

    /*
     * Find summation of all numbers
     */
    for(i=1; i<=n; i++)
    {
        sum += i;
    }

    printf("Sum of first %d natural numbers = %d", n, sum);

    return 0;
}

Note: sum += i is equivalent to sum = sum + i. You can use any of them depending on your comfort.

Output

Enter upper limit: 10
Sum of first 10 natural numbers = 55

Program to find sum of natural numbers in given range

/**
 * C program to find sum of natural numbers in given range
 */

#include <stdio.h>

int main()
{
    int i, start, end, sum=0;

    /* Input lower and upper limit from user */
    printf("Enter lower limit: ");
    scanf("%d", &start);
    printf("Enter upper limit: ");
    scanf("%d", &end);

    /*
     * Find summation of all numbers
     */
    for(i=start; i<=end; i++)
    {
        sum += i;
    }

    printf("Sum of natural numbers between %d-%d = %d", start, end, sum);

    return 0;
}

Output

Enter lower limit: 10
Enter upper limit: 15
Sum of natural numbers between 10-15 = 75

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>