In this program, user is asked to enter a positive integer and sum of natural numbers up to that integer is displayed by this program. Suppose, user enters 5 then,
Sum will be equal to 1+2+3+4+5 = 15
#include<stdio.h>
#include<conio.h>
int sum(int);
void main()
{
int n;
printf("Enter number: ");
scanf("%d",&n);
printf("Sum of natural numbers up to %d is %d",n,sum(n));
getch();
}
int sum(int n)
{
if(n!=0)
return n+sum(n-1); /*recursion used*/
}
OUTPUT:
No comments:
Post a Comment