C Program to Calculate Sum of Natural Numbers
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
#include <stdio.h>
int main()
{
int i, s = 0;
int n = 10;
i = 1;
while (i <= n) {
s += i;
i++;
}
printf ( "Sum = %d" , s);
return 0;
}
|
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
#include <stdio.h>
int main()
{
int i, s = 0;
int n = 10;
for (i = 0; i <= n; i++) {
s += i;
}
printf ( "Sum = %d" , s);
return 0;
}
|
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
#include <stdio.h>
int sumofnaturalnumbers( int num)
{
if (num != 0)
return num + sumofnaturalnumbers(num - 1);
else
return num;
}
int main()
{
int number = 10;
printf ( "Sum = %d" , sumofnaturalnumbers(number));
return 0;
}
|
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
#include <stdio.h>
int sumofnaturalnumbers( int num)
{
int i, s = 0;
for (i = 0; i <= num; i++) {
s += i;
}
printf ( "Sum = %d" , s);
}
int main()
{
int number = 10;
sumofnaturalnumbers(number);
return 0;
}
|
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
#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;
}
|
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.
Last Updated :
27 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...