C langauge known for it’s simplicity and efficency comes with all features for performing mathematical operations. One such operation is to find the sum of n natural numbers, In this article we will write a C program that calculates sum of n natural number.
Table of Contents
The sum of n Natural Numbers Formula
The sum of first n natural numnber is a classic mathematical problem we can calculate it by using following formula.
sum = n*(n+1)/2
In this article, by using C language and given the above formula we will calculate the sum of n natural numbers.
C Program for Sum of n Natural Numbers
#include <stdio.h>
void main()
{
int n, sum = 0;
printf("Enter the value of n ");
scanf("%d", &n);
sum = (n * (n + 1)) / 2;
printf("the sum of first %d natural numnbers = %d", n, sum);
}
Output
How does the above C Program Work?
- The above C program for calculating the sum of n natural numbers starts by asking the user to enter the value of n.
- With the help of the scanf program stores the value of n in a variable named n of type int.
- By using a formula program calculates the sum of n natural numbers and stores it in variable sum.
- At the end, program prints the result.
Happy Coding
4 thoughts on “C Program for Sum of n Natural Numbers”