We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,687 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How to do recursion??

Anyone know how to do this question?
Use recursion to implement the following recurrence relation f(x):
f(x)=1 where =1
f(x) = f((x+1)/2) +1 where x is odd
f(x) = f(x/2) +1 where x is even

This is what i did:

#include<stdio.h>

int func (int x)

int main()
{
	int x;
	printf("Please enter the value of x: ");
	scanf("%d", &x);

	int func=func(x);
	printf("%d",func) ;

	return 0;
}

int func (int x)
{
	if(x==1) 
		return 1;
	else if (x%2 ==1)
		return func ( (x+1)/2 ) + 1;
	else
		return func (x/2) + 1;
}

But it doesnt work.
Could you please kindly explain how a recursion work as well?
Thank youuuuu!

4
Contributors
4
Replies
21 Hours
Discussion Span
1 Year Ago
Last Updated
5
Views
charleneok
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
int func1(int x){
    //do something with int
   return func1(x-1);
}

see also this and this one

Stefano Mtangoo
Senior Poster
3,731 posts since Jun 2007
Reputation Points: 462
Solved Threads: 396
Skill Endorsements: 0

Inside a function when you call the same function then it is known as recursion function

selina12
Newbie Poster
13 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

Anyone know how to do this question?
Use recursion to implement the following recurrence relation f(x):
f(x)=1 where =1
f(x) = f((x+1)/2) +1 where x is odd
f(x) = f(x/2) +1 where x is even

This is what i did:

#include<stdio.h>

int func (int x)

int main()
{
	int x;
	printf("Please enter the value of x: ");
	scanf("%d", &x);

	int func=func(x);
	printf("%d",func) ;

	return 0;
}

int func (int x)
{
	if(x==1) 
		return 1;
	else if (x%2 ==1)
		return func ( (x+1)/2 ) + 1;
	else
		return func (x/2) + 1;
}

But it doesnt work.
Could you please kindly explain how a recursion work as well?
Thank youuuuu!

What doesn't work about it? All I see wrong with your code is a missing ";" after your function prototype.

Greywolf333
Junior Poster
145 posts since Sep 2010
Reputation Points: 40
Solved Threads: 39
Skill Endorsements: 0

Yeah Right
Semicolon at the end of the function declaration is missing

selina12
Newbie Poster
13 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0652 seconds using 2.65MB