GeeksforGeeks » Miscellaneous

Recursion help!!

(3 posts)

Tags:

  1. raj
    Member
    Posted 1 year ago #

    int Max(int a[],int n)
    {
    	int max;
    	if(n==1)
    		return a[0];
    	else
    		max=Max(a,n-1);
    	if(max>a[n-1])
    		return max;
    	else
    		return a[n-1];
    }
    

    Hi, the above is a code to find the max in an array recursively. I find very difficult in understanding the flow of recursive programs. Can someone help me out in explaining the flow of the program with stack sections if possible.
    Thanks!!

  2. kartik
    Moderator
    Posted 1 year ago #

  3. Shekhu
    Member
    Posted 1 year ago #

    int Max(int a[],int n)
    {
           int max;
           if(n==1) -------------------------------------------------------( 1 )
                   return a[0];
           else
                   max=Max(a,n-1);
    -------------------------------------------------------( 2 )
           if(max>a[n-1])
                   return max;
    -------------------------------------------------------( 3 )
    }
    
           else
                   return a[n-1];
    -------------------------------------------------------( 4 )
    
    }
    

    Statement (1) will executed when there is only single present in the array

    Statement (2) otherwise else part will executed
    in this section we calling same function with array index n,n-1,......,0
    (position of the elements)

    Statement (3) checking whether this present element is larger than previous
    one ie here we are comparing ( n )th and
    (n-1) th element; if (n) th is greater then it will return its value

    Statement (4)
    here if (n-1) th is greater so it will return its value

    Source: http://groups.google.co.in/group/algogeeks/browse_thread/thread/626f2cc928c7b68e


Reply

You must log in to post.

RSS feed for this topic