In this article, you will learn to calculate Sum of First n Natural numbers.
The positive numbers 1, 2, 3… are known as natural numbers. The sum of natural numbers up to 10 is:
sum = 1 + 2 + 3 + ... + 10
Find the sum of numbers for every number from 1 to 4 :
Sum of numbers till 1 = 1 Sum of numbers till 2 = 1 + 2 = 3 Sum of numbers till 3 = 1 + 2 + 3 = 6 Sum of numbers till 4 = 1 + 2 + 3 + 4 = 10
Implementation :
1. Using for loop :
// C Program to find Sum of N Numbers using For Loop #include<stdio.h> int main() { // take input int Number = 10 ; // intialze sum to 0 int i, Sum = 0; for(i = 1; i <= Number; i++) { // sum with previous sum Sum = Sum + i; } printf("Sum of Natural Numbers til given number is = %d", Sum); // successful completion return 0; }
Output :
Sum of Natural Numbers til given number is = 55
Note that you can use ‘while loop’ and ‘do while loop’ in place of ‘for loop’.
2. Using Mathematical formula :
// Using mathemamtical formula #include <stdio.h> int main() { // take input int n = 10; // calculate sum using mathematical formula int sum = (n*(n+1))/2; printf("Sum of Natural Numbers til given number is = %d", sum); // successful completion return 0; }
Output :
Sum of Natural Numbers til given number is = 55
Note that mathematical formula to find the sum of sum of n natural number :
sum = n*(n+1)/2
3. Using Functions :
// C Program to find Sum of N Numbers using Functions #include<stdio.h> // function of sum int Sumof(int Number) { // intialze sum to 0 int i, sum = 0; for(i = 1; i <= Number; i++) { // sum with previous sum sum = sum + i; } return sum ; } ; // driver code int main() { // take input int Number = 10 ; int result = Sumof(Number); printf("Sum of Natural Numbers til given number is = %d", result); // successful completion return 0; }
Output :
Sum of Natural Numbers til given number is = 55
4. Using Recursion :
// C Program to find Sum of N Numbers using Functions #include<stdio.h> // recursive function of sum int Sumof(int Number) { // base condition if (Number == 0) return Number; else // for big numbers return (Number + Sumof(Number - 1)); } ; // driver code int main() { // take input int Number = 10 ; int result = Sumof(Number); printf("Sum of Natural Numbers til given number is = %d", result); // successful completion return 0; }
Output :
Sum of Natural Numbers til given number is = 55
Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.