Welcome to Dream.In.Code
Click Here
Getting C++ Help is Easy!

Join 118,307 C++ Programmers for FREE! Ask your question and get quick answers from experts. There are 1,679 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Recursion

 
Reply to this topicStart new topic

Recursion, how do you transform this program so that it terminates after 17 calls

metch
post 5 Aug, 2008 - 08:13 PM
Post #1


New D.I.C Head

*
Joined: 24 Jun, 2008
Posts: 7

cpp

#include <stdio.h>

int main(void)

{
printf(" I am hungry! ");
main();
return 0;

}

** Edit ** code.gif
User is offlineProfile CardPM

Go to the top of the page


no2pencil
post 5 Aug, 2008 - 08:21 PM
Post #2


Wet D.I.C.

Group Icon
Joined: 10 May, 2007
Posts: 5,488



Thanked 36 times

Dream Kudos: 2350

Expert In: Goofing Off

My Contributions


You don't want to call main from within itself. I would make a 2nd function like so.

cpp

#include <stdio.h>

#define MAX 17

void hungry(void);
int main(void)
{
int i=0;
for(i;i<=MAX;i++) hungry();
return 0;
}

void hungry(void) {
printf(" I am hungry! ");
}


I think this is a little more along the lines of recursion. What I had before was just a simple loop.

Please correct me if I'm wrong here.

cpp

#include <stdio.h>

#define MAX 17

int hungry(int x);
int main(void)
{
hungry(0);
return 0;
}

int hungry(int x) {
printf("%i : I am hungry!\n",x);
x++;
if(x<MAX) hungry(x);
return x;
}
User is offlineProfile CardPM

Go to the top of the page

metch
post 7 Aug, 2008 - 06:57 PM
Post #3


New D.I.C Head

*
Joined: 24 Jun, 2008
Posts: 7


Thanks .....worked perfectly




QUOTE(no2pencil @ 5 Aug, 2008 - 08:21 PM) *

You don't want to call main from within itself. I would make a 2nd function like so.

cpp

#include <stdio.h>

#define MAX 17

void hungry(void);
int main(void)
{
int i=0;
for(i;i<=MAX;i++) hungry();
return 0;
}

void hungry(void) {
printf(" I am hungry! ");
}


I think this is a little more along the lines of recursion. What I had before was just a simple loop.

Please correct me if I'm wrong here.

cpp

#include <stdio.h>

#define MAX 17

int hungry(int x);
int main(void)
{
hungry(0);
return 0;
}

int hungry(int x) {
printf("%i : I am hungry!\n",x);
x++;
if(x<MAX) hungry(x);
return x;
}


User is offlineProfile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 10/10/08 11:40AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month