In this C programming, we are going to calculate the sum of n natural numbers using different methods. Before moving to the code part, let's first understand natural numbers.
What are Natural Numbers?
Natural numbers are a set of positive whole numbers starting from 1 and extending indefinitely, including 1, 2, 3, 4, and so on. They do not include zero or any negative numbers.
Example:
Input: n = 10 Output: 55 Explanation: 1 + 2 + 3+ 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
Sum of Natural Numbers using while Loop.
//C program to sum natural numbers using while loop #include <stdio.h> int main() { int n, sum = 0, i = 1; printf("Enter a positive integer: "); scanf("%d", &n); while (i <= n) { sum += i; i++; } printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum); return 0; }
Enter a positive integer: 8
Sum of natural numbers from 1 to 8 is 36.
Sum of Natural Numbers using for Loop.
//C program to find sum of natural numbers using for loop #include <stdio.h> int main() { int n, sum = 0; printf("Enter a positive integer: "); scanf("%d", &n); for (int i = 1; i <= n; i++) { sum += i; } printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum); return 0; }
Enter a positive integer: 11
Sum of natural numbers from 1 to 11 is 66.
Sum of Natural Numbers using Recursion.
//C program to find the sum of natural numbers using Recursion #include <stdio.h> //recursive function int sumFunction(int n) { int sum = 0; for (int i = 1; i <= n; i++) { sum += i; } return sum; } int main() { int n, sum; printf("Enter a positive integer: "); scanf("%d", &n); sum = sumFunction(n); printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum); return 0; }
Enter a positive integer: 12
Sum of natural numbers from 1 to 12 is 78.