Here we will build a C program to calculate the sum of natural numbers using 4 different approaches i.e.
- Using while loop
- Using for loop
- Using recursion
- Using Functions
We will keep the same input in all the mentioned approaches and get an output accordingly.
Input:
n = 10
Output:
55
Explanation: The sum of natural numbers up to a given number is 0+1+2+3+4+5+6+7+8+9+10=55
Approach 1: Using while loop
The while loop executes the statements until the condition is false
// C Program to demonstrate
// Sum of Natural Numbers
// using while loops
#include <stdio.h>
int main()
{
int i, s = 0;
int n = 10;
i = 1;
// while loop executes
// the statements until the
// condition is false
while (i <= n) {
// adding natural numbers
// up to given number n
s += i;
i++;
}
// printing the result
printf("Sum = %d", s);
return 0;
}
Output
Sum = 55
Time Complexity : O(n) as the loop runs for n iterations
Auxiliary Space : O(1) as only a fixed amount of memory is used.
Approach 2: Using for loop
For loop iterates up to n number of times.
// C Program to demonstrate
// Sum of Natural Numbers
// using for loops
#include <stdio.h>
int main()
{
int i, s = 0;
int n = 10;
for (i = 0; i <= n; i++) {
// adding natural numbers
// up to given number n
s += i;
}
// printing the result
printf("Sum = %d", s);
return 0;
}
Output
Sum = 55
Time Complexity : O(n) as the loop runs for n+1 iterations.
Auxiliary Space : O(1) as only a fixed amount of memory is used.
Approach 3: Using recursion
// C Program to demonstrate
// Sum of Natural Numbers
// using recursion
#include <stdio.h>
int sumofnaturalnumbers(int num)
{
if (num != 0)
// adding natural numbers up to given number n
return num + sumofnaturalnumbers(num - 1);
else
return num;
}
int main()
{
int number = 10;
// printing the result
printf("Sum = %d", sumofnaturalnumbers(number));
return 0;
}
Output
Sum = 55
Time Complexity : O(n) as the function is called n+1 times.
Auxiliary Space : O(n) as each function call stores one value in the call stack, which consumes memory.
Approach 4: Using functions
// C Program to demonstrate
// Sum of Natural Numbers
// using functions
#include <stdio.h>
int sumofnaturalnumbers(int num)
{
int i, s = 0;
for (i = 0; i <= num; i++) {
// adding natural numbers
// up to given number n
s += i;
}
// printing the result
printf("Sum = %d", s);
}
int main()
{
int number = 10;
// calling the function
sumofnaturalnumbers(number);
return 0;
}
Output
Sum = 55
Time Complexity : O(n) as the loop runs for n+1 iterations.
Auxiliary Space : O(1) as only a fixed amount of memory is used.
Approach 5 : Using the formula sum of n natural numbers = n*(n+1)/2
// C Program to demonstrate
// Sum of Natural Numbers
#include <stdio.h>
int main()
{
int num = 10;
int s,x;
s=num*(num+1);
x=(int)(s/2);
printf("Sum = %d", x);
return 0;
}
Output
Sum = 55
Time Complexity : O(1) as it performs a fixed number of operations regardless of the input size.
Auxiliary Space : O(1) as only a fixed amount of memory is used.