Program to find Sum of N natural numbers in c using function

Program to Find Sum of N natural numbers in c using function | Sum of Natural Numbers using function in C

Program to find Sum of N natural numbers in c using function

 Here we are going to write a program to find sum of n natural numbers in c using function. This is a very simple program. We can do this normally also without function that is just c program to find sum of n natural numbers. Also this program can be done using recursion, c program to find sum of natural numbers using recursion. But here we will do this program using function. 

Sum of n natural numbers - n(n+1)/2

If we want to find sum of first 5 natural numbers then according to the formula,

(5 x 6)/2 = 15

*And if we calculate normally, 1 + 2 + 3 + 4 + 5 = 15

We will use this formula to calculate sum in this way we can avoid running loop. So if you wanted to do sum of n natural numbers program without using for loop then here it is.

First we will create a function named sm() of int return type and it will take one integer. Then within that function we will calculate sum and return the answer. Then in main() function we will call the sm() function, that's it. Now lets code it.

Try out on your own before going down.

Program to find Sum of N natural numbers in c using function 

#include <stdio.h>

int sm(int n){
   return (n*(n+1))/2;
}

int main(){
    int n;
    printf("Enter number of terms: ");
    scanf("%d",&n);
    printf("Sum : %d",sm(n));
    return 0;
}


Output

Enter number of terms: 5
Sum : 15


Program to find Sum of N natural numbers in c using function (using for loop)

#include <stdio.h>

int sm(int n){
   int s=0;
   for(int i=1;<=n;i++){
       s+=i;
   }
   return s;
}

int main(){
    int n;
    printf("Enter number of terms: ");
    scanf("%d",&n);
    printf("Sum : %d",sm(n));
    return 0;
}


Output

Enter number of terms: 5
Sum : 15


More like this 

• Program to reverse a number using function

• Armstrong Number Check using function

• Palindrome Number Check using function

• Perfect Number Check using function 

• Perfect Number Check

C programs list

Post a Comment

If you have any doubts, please let me know

Previous Post Next Post