how does the recursion in the code is actually working

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Siddarth777
    New Member
    • Sep 2010
    • 28

    #1

    how does the recursion in the code is actually working

    heres a code for boundary filling
    my doubt is how the control is going from one fill_right function to other
    Code:
    #include<stdio.h>
    #include<conio.h>
    #include<graphics.h>
    #include<dos.h>
    
    void fill_right(x,y)
    int x , y ;
    {
    if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED))
    {
    putpixel(x,y,RED);
    fill_right(++x,y);
    delay(1);
    x = x - 1 ;
    fill_right(x,y-1);
    fill_right(x,y+1);
    }
    delay(1);
    }
    
    
    void fill_left(x,y)
    int x , y ;
    {
    if((getpixel(x,y) != WHITE)&&(getpixel(x,y) != RED))
    {
    putpixel(x,y,RED);
    
    fill_left(--x,y);
    x = x + 1 ;
    fill_left(x,y-1);
    fill_left(x,y+1);
    }
    delay(1);
    }
    
    
    void main()
    {
    int x,y,n,i;
    int gd=DETECT,gm;
    clrscr();
    
    initgraph(&gd,&gm,"c:\\tc\\bgi");
    
    
    
    /*- draw object -*/
    
    line (50,50,200,50);
    line (200,50,200,100);
    line (200,100,50,100);
    line (50,100,50,50);
    
    /*- set seed point -*/
    x = 125; y = 75;
    
    fill_right(x,y);
    fill_left(x-1,y);
    
    getch();
    }
    please help me......thanks a lot
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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().

    Comment

    Working...