pages

Thursday, 8 April 2021

Program to calculate the sum of first n natural number by function in c-language.

Q.no Program to calculate the sum of first n natural number in c-language 

by using function .

In this program .we will calculate the sum of first n natural number by using  function , and user entered the number.


In this program, we defined a function sum() which takes argument. with using for loop , the function sum() calculate the sum of the series 1+2 +3 +4+.....  later its returned the back to the caller function.



 #include<stdio.h>

#include<conio.h>

int sum(int a);

main()

{

    int x,y;

    printf("enter a number");

    scanf("%d",&x);

    y=sum(x);

    printf("sum of the first %d natural number is %d",x,y);

    getch();

}

int sum(int a)

{

    int i,s=0;

    for(i=1;i<=a;i++)

        s=s+i;

    return(s);

}

output: emter the number : 6

   the sum of the first 6 natural number is 21


For more c-programming  example:-

c-program to calculate the factors of the number



No comments:

Post a Comment