somebody help me in this recursive pgm???

Status
Not open for further replies.

ashwini jayaraman

Member level 2
Joined
Jan 17, 2013
Messages
49
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,286
Activity points
1,601
int rec(int n1)
{
int x=8;

if(n1<=80)
{
int n1=x+rec(n1);
return(n1);
}
else
return 0;
}
#include<stdio.h>
int rec(int n);
void main()
{
int n;
printf("enter no");
scanf("%d",&n);
rec;
printf("%d",rec);
}

I want 8*10= 80 to be printed!!!!
 

Can you expalain what you are trying to do?

Code C - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int rec(int n1)
{
    int x=8;
 
    if(n1<=80)
    {
        int n2=x+rec(n1);   //if n1 = 80 then n2 = 88
        return(n2);
    }
    else
    return 0;
}
#include<stdio.h>
 
int rec(int n);
 
void main()
{
    int n, m;
    printf("enter no");
    scanf("%d",&n);
    m = rec(n);
    printf("%d", m);
}

 

if(n1<=80)
{
n1=x+rec(n1);
return(n1);
}
This will put your program in an infinite loop.
The problem with the code is
1. you are using n1 as a case condition.
2. your program is recursively calling itself without modifying n1. n1 can't be updated unless the following line is executed.
n1=x+rec(n1);
what you can do for example is

n1 = n1 * x;
rec(n1);
*but if you write it like
n1 = n1 + x;
you will get 18, as only the first computation(round) result is being returned.
 
Last edited:

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…