Calculates the sum of the first N natural numbers using different approaches in C.
- The sum can be calculated using a while loop, for loop, recursion, or a separate function.
- All approaches use the same input and produce the same result using different programming techniques.
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
#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
Approach 2: Using for loop
For loop iterates up to n number of times.
#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
Approach 3: 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
Approach 4: 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
Approach 5 : Using the formula sum of n natural numbers = n*(n+1)/2
#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