Write a recursive function to obtain the running sum of first 25 natural numbers.
void main()
{
int d,e;
d=25;
e=naturaln(d);
printf("\nThe sum of the first %d digits is %d",d,e);
}
naturaln(int x)
{
int a;
if(x==1)
return(1);
else
{
a=x+naturaln(x-1);
return(a);
}
}
Subscribe to:
Post Comments (Atom)
in this recursive function,will not the value of x
ReplyDeletebe negative after it has reached zero?what if i write
if(x==25)
return(25);
else
a=x+natural(x+1);
return(a);
}
It'll never reach zero because after reaching 1 the program comes out of the function
ReplyDeleteCorrect
DeleteWill it be wrong if I write. {
ReplyDeleteint a;
if(x==0)
return(1);
Yes it will be wrong becoz it will add an extra 1 to the series
ReplyDeleteI just want to know what if I write
ReplyDeleteint getsum ( int n)
{ int sum=0;
if (n==25)
return sum;
sum =n+getsum (++n);
return (sum);
}
How it will add 25 to the series when it will return 0 for getsum (25);
this is right
ReplyDeleteint getsum(int);
ReplyDeleteint main()
{
int s;
s=getsum(0);
printf("the sum of first 25 natural
is %d\n",s);
return 0;
}
int getsum(int n)
{
int sum=0;
if(n==25);
return sum;
sum=n+getsum(++n);
return (sum);
}
int getsum(int);
ReplyDeleteint main()
{
int s;
s=getsum(0);
printf("the sum of first 25 natural
is %d\n",s);
return 0;
}
int getsum(int n)
{
int sum=0;
if(n==25);
return sum;
sum=n+getsum(++n);
return (sum);
}