By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,587 Members | 1,071 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,587 IT Pros & Developers. It's quick & easy.

how does the recursion in the code is actually working

Siddarth777
P: 28
heres a code for boundary filling
my doubt is how the control is going from one fill_right function to other
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. #include<conio.h>
  3. #include<graphics.h>
  4. #include<dos.h>
  5.  
  6. void fill_right(x,y)
  7. int x , y ;
  8. {
  9. if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED))
  10. {
  11. putpixel(x,y,RED);
  12. fill_right(++x,y);
  13. delay(1);
  14. x = x - 1 ;
  15. fill_right(x,y-1);
  16. fill_right(x,y+1);
  17. }
  18. delay(1);
  19. }
  20.  
  21.  
  22. void fill_left(x,y)
  23. int x , y ;
  24. {
  25. if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED))
  26. {
  27. putpixel(x,y,RED);
  28.  
  29. fill_left(--x,y);
  30. x = x + 1 ;
  31. fill_left(x,y-1);
  32. fill_left(x,y+1);
  33. }
  34. delay(1);
  35. }
  36.  
  37.  
  38. void main()
  39. {
  40. int x,y,n,i;
  41. int gd=DETECT,gm;
  42. clrscr();
  43.  
  44. initgraph(&gd,&gm,"c:\\tc\\bgi");
  45.  
  46.  
  47.  
  48. /*- draw object -*/
  49.  
  50. line (50,50,200,50);
  51. line (200,50,200,100);
  52. line (200,100,50,100);
  53. line (50,100,50,50);
  54.  
  55. /*- set seed point -*/
  56. x = 125; y = 75;
  57.  
  58. fill_right(x,y);
  59. fill_left(x-1,y);
  60.  
  61. getch();
  62. }
  63.  
  64.  
please help me......thanks a lot
Oct 18 '10 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
The wasiest way to see how recursion works is to use Post-It sheets.

When you call the fill function, take a Post-It and write down the names and values of the variables.

Next, go through the code a line at a time and make chnages to the variables based on the code.

When you get to a call to the fill function inside the fill function, stop writing on the Post-It and start a new one for the new call.

Now go back to the start of the fill function and write doiwn the values as you did before but these will be the values from the second call.

Step through the code again and if you get to another call to the fill function start another Post-It.

When you finally get to a return in the fill function, you go back to the previous Post-It and resume stepping through the fill function after the place where it was called.

Eventually, you will work your way back to main().
Oct 18 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.