C Program to Calculate the Sum of Natural Numbers

CodingTute

C Program to Calculate the Sum of Natural Numbers

In this example, you will learn to calculate the sum of first n natural numbers.

Mathematically, the sum of n natural numbers can be calculated by sum = n(n+1)/2

C Program to Calculate the Sum of Natural Numbers

#include <stdio.h>

int main()
{
    int n, sum;
    
    printf("Enter N: ");
    scanf("%d",&n);
    if(n < 0)
       printf("Entered Number is -ve");
    else{
       // calculating sum of n natural numbers
       sum = n * (n + 1) / 2;
       printf("Sum = %d", sum);
    }
    return 0;
}

Output

Enter N: 10
Sum = 55

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.