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

Previous Program Next Program

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

Logic to find sum of natural numbers

I already discussed, how efficiently you can use for loop to iterate over a series. To print all natural numbers. In case you missed, take a quick recap.

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

  1. Read the 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. Which is 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 the previous sum with the current number i. Which is sum = sum + i.
  5. Finally after the 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;

    /* Read 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 similar 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;

    /* Read 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 first 10 natural numbers = 75

Happy coding ;)

You may also like

Previous Program Next Program

Labels: , ,