Natural numbers are the whole numbers starting from 1. They are 1, 2, 3, 4, ….. and so on.
This program asks the user to input the number of terms whose sum the user would like to find.
C program to find the sum of n natural numbers (By normal method)
#include<stdio.h> int main() { int i=1, sum=0, n; printf ("Enter the number of terms whose sum you would like to evaluate n"); scanf ("%d", &n); do { sum = sum+i; i=i+1; } while (i<=n); printf("The sum of first %d natural numbers is %d", n, sum); return 0; }
The program asks the user to enter the number of terms he/she would like to evaluate the sum of, which is stored in variable n. Another variable i is assigned value 1, which is used for counting the number of terms in the loop and also as a natural number which is added to the result. The variable sum stores sum of the natural numbers. The sum is initialized to 0 to avoid addition of garbage numbers.
As the program enters the loop, value of i is added to the variable sum which now equals the sum of all natural numbers till i. Then the value of i is increased by 1. The loop continues as long as the value of i is less than or equal to n as we are calculating the sum of first n natural numbers. When, the loop exits, the result is displayed on the screen.
Output
Enter the number of terms whose sum you would like to evaluate 10 The sum of first 10 natural numbers is 55
C program to find the sum of n natural numbers (By direct method)
This result can also be achieved by using a direct mathematical formula for calculation of sum of n natural numbers. The formula is
$sum_{k = 1}^{n}k = tfrac{n(n+1)}{2}$
#include<stdio.h> int main() { int sum=0, n; printf ("Enter the number of terms whose sum you would like to evaluate n"); scanf ("%d", &n); sum = (n * (n + 1) / 2 ); printf("The sum of first %d natural numbers is %d", n, sum); return 0; }
Output
Enter the number of terms whose sum you would like to evaluate 10 The sum of first 10 natural numbers is 55