calculate sum of natural number using recursion in c programming

In this example, we calculate the sum of natural numbers entered by the user.

C Program to Sum of Natural Numbers Using for Loop

The positive numbers like 1,2,3,4,5... are known as natural numbers. In this example we take one natural number as input from user and print sum like :

	
sum = 1 + 2 + 3 + ... + 10
    

Example :

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

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

    for (i = 1; i <= n; ++i) {
        sum += i;
    }
    printf("Sum = %d", sum);
    return 0;
}
	

Output :

	
Enter a positive integer: 10
Sum = 55
	

The above program we take input from the user and stores it in the variable n. Then, for loop is used to calculate the sum up to n. As per above output loop runs for 10 times.

C Program to Sum of Natural Numbers Using while Loop

	
#include <stdio.h>
int main() {
    int n, i, sum = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    i = 1;

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

    printf("Sum = %d", sum);
    return 0;
}
	

Output :

	
Enter a positive integer: 50
Sum = 1275
	

In both examples, the loop is iterated n number of times. And, in each iteration, the value of i is added to sum and i is incremented by 1. Though both programs are technically correct, it is better to use for loop in this case. It's because the number of iterations is known.

C Program to Sum of Natural Numbers Using do...while Loop

	
#include <stdio.h>
int main() {
    int n, i, sum = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    i = 1;

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

    printf("Sum = %d", sum);
    return 0;
}
	

Output :

	
Enter a character: 5
Sum : 15
	

C Program to Sum of Natural Numbers Using Recursion

	
#include<stdio.h>  

int sum(int num)  
{  
    if(num)  
        return(num + sum(num-1));  
    else  
        return 0;  
}  
int main()  
{  
    int count;  
    
    printf("Enter a positive no :: ");  
    scanf("%d", &count);  
    
    printf("Sum of 1st %d natural numbers is %d\n", count, sum(count));  
    
    return 0;  
}  
	

Output :

	
Enter a positive no :: 50
Sum of 1st 50 natural numbers is 1275
	

Share your thoughts

Ask anything about this examples