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 withing given interval using loop.

Example:
Input n: 10
Output sum of natural number 1-10: 55


Required knowledge

Basic C programming, For loop

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;

    /* Reads any number from user */
    printf("Enter any number to find sum of first n natural numbers: ");
    scanf("%d", &n);

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

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

    return 0;
} 

Note: sum += i is similar to sum = sum + i. You can any of them to find sum.

Output
Enter any number to find sum of first n natural numbers: 10

Sum of first 10 natural numbers = 55


Also don't forget to check this program using recursive programming technique - C program to find sum of natural numbers within given interval using recursion.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment