C Program - Calculate sum of Natural numbers
In Mathematics, the natural numbers are all positive numbers which is used for counting like 1, 2, 3, 4, and so on. The smallest natural number is 1.
Objective: Write a C program which returns sum of natural numbers starting from 1 to given natural number n, (1 + 2 + 3 + ... + n).
Method 1: Using while loop
The example below shows how to use while loop to calculate sum of first n natural numbers.
#include <stdio.h> int main (){ int n = 10; int i = 1; int sum = 0; //calculating sum from 1 to n while(i <= n) { sum += i; i++; } printf("Sum is: %i\n", sum); return 0; }
The above code will give the following output:
Sum is: 55
Method 2: Using for loop
The same can be achieved using for loop. Consider the example below:
#include <stdio.h> int main (){ int n = 10; int sum = 0; //calculating sum from 1 to n for(int i = 1; i <= n; i++) sum += i; printf("Sum is: %i\n", sum); return 0; }
The above code will give the following output:
Sum is: 55
Method 3: Using Recursion
Similarly, recursion can be used to calculate the sum.
#include <stdio.h> //recursive function static int Sum(int n) { if(n == 1) return 1; else return (n + Sum(n-1)); } int main (){ printf("Sum of first 10 natural numbers: %i\n", Sum(10)); printf("Sum of first 20 natural numbers: %i\n", Sum(20)); return 0; }
The above code will give the following output:
Sum of first 10 natural numbers: 55 Sum of first 20 natural numbers: 210
Method 4: Using Mathematical Formula
The sum of first n natural numbers can be mathematically expressed as:
#include <stdio.h> int main (){ int n = 10; //calculating sum from 1 to n int sum = n*(n+1)/2; printf("Sum is: %i\n", sum); return 0; }
The above code will give the following output:
Sum is: 55
Recommended Pages
- C Program - To Check Prime Number
- C Program - Bubble Sort
- C Program - Selection Sort
- C Program - Maximum Subarray Sum
- C Program - Reverse digits of a given Integer
- C - Swap two numbers
- C Program - Fibonacci Sequence
- C Program - Insertion Sort
- C Program - Find Factorial of a Number
- C Program - Find HCF of Two Numbers
- C Program - Merge Sort
- C Program - Shell Sort
- Stack in C
- Queue in C
- C Program - Find LCM of Two Numbers
- C Program - To Check Whether a Number is Palindrome or Not
- C Program - To Check Whether a String is Palindrome or Not
- C Program - Heap Sort
- C Program - Quick Sort
- C - Swap Two Numbers without using Temporary Variable