# Sum of N Natural Numbers in C

Write a C program to find the sum of N natural numbers in C using for loop, while loop, do-while loop, and without loop. Prerequisites:- While loop in C, Do-while loop in C, Difference between while and do-while, For loop in C

Sum of natural number N as given as sum = 1+2+3+….+N

Examples:-
1+2+3+4+5 = 15
1+2+3+4+5+6+7+8+9+10 = 55

To find the sum of natural numbers declare a variable and initialize it with value 1. Declare another variable sum and initialize it with 0. Now, in every iteration increase sum value until the value N.

## Sum of N Natural Numbers in C using for loop

``````#include<stdio.h>
int main()
{
int n, sum=0;

printf("Enter n value: ");
scanf("%d", &n);

for(int i=0; i<=n; i++)
{
sum += i; //sum = sum + i
}

printf("Sum of first %d natural numbers = %d",
n, sum );

return 0;
}``````

Output for the different test-cases:-

Enter n value: 10
Sum of first 10 natural numbers = 55

Enter n value: 0
Sum of first 0 natural numbers = 0

The sum of N natural numbers also can be calculated in reverse order. For example The sum of 5 natural numbers= 5+4+3+2+1

In this case, the loop control variable should initialize with “n” and the decrement operator should be used. The below program shows it,

``````#include<stdio.h>
int main()
{
int n, sum=0;

printf("Enter n value: ");
scanf("%d", &n);

for(int i=n; i>=0; i--)
{
sum += i;
}

printf("Sum of first %d natural numbers = %d",
n, sum );

return 0;
}``````

## Using While Loop

``````#include<stdio.h>
int main()
{
int n, sum=0, i=0;

printf("Enter n value: ");
scanf("%d", &n);

while(i<=n)
{
sum += i++;
}

printf("Sum of first %d natural numbers = %d",
n, sum);

return 0;
}``````

The statements of the while loop given in this program can be also written as given below,

``````while (i<=n) {
sum = sum + i;
i++;
}``````

## Using the do-while loop

``````#include<stdio.h>
int main()
{
int n, sum=0, i=0;

printf("Enter n value: ");
scanf("%d", &n);

do
{
sum += i++;
} while(i<=n);

printf("Sum of first %d natural numbers = %d",
n, sum );

return 0;
}``````

The time complexity for all above program was O(n).

## Sum of N natural numbers in C without loop

We can also do the same work without using the loop. The formula for this operation,

sum = `n*(n+1)/2;`

Example:-
Sum of first 10 natural numbers = 10*(10+1)/2 = 10*11/2 = 5*11 = 55

``````#include<stdio.h>
int main()
{
int n, sum;

printf("Enter a positive number: ");
scanf("%d", &n);

sum = n*(n+1)/2;

printf("Sum = %d", sum);

return 0;
}``````

Output for the different cases:-

Enter a positive number: 10
Sum = 55

Enter a positive number: 15
Sum = 120

The time complexity for this program is O(1).

We can do the same task using Recursion also:- Find the sum of Natural number using recursion

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!