Confusion in recursion

int main()
{
int p=get();//get() function is called here itself.(get is user-defined function for input purpose.)
}

BUT when we talk of recursion,

 int abhilash(int a,int b)
    {
    	int ret=abhilash(a,b>>1);//But here why abhilash is not called?and my program proceeds to                     "rest of the code".
    	/*rest of the code*/
    }

IF you’re still confused then click on this link to get the answer.

ELSE, explanation: there is a base case which is invoked when the condition in that case is matched. Otherwise, a recursive call is made again.

Example:

Here’s a function which will sum the first n elements of an array.

int sum(int arr[], int size) {
    int result;
    if (size == 0)  // base case
        result = 0;
    else {
        // recursive call
        int smallResult = sum (arr, size - 1);

        // use solution of recursive call to solve this problem
        result = smallResult + arr[size - 1];
     }
     return result;
}

If the arr was {1, 2, 3} so the size was 3 initially. sum() will be called with size = 3, then base case is checked, which is false, so a call to sum() with size = 2 is made, which in turn calls sum() with size = 1 and so on… When the sum() is called with size = 0, the base case is true, hence the ultimate call returns the value of result to the function which had called it, which in turn returns the value to the function which had called the penultimate function and so on… and hence the first call returns the answer to wherever the function was called from, within the program. :slight_smile:

1 Like

1)int sum(int arr[], int size) {

  1. int result;

  2. if (size == 0) // base case

  3.    result = 0;
    
  4. else {

  5.    // recursive call
    
  6.    int smallResult = sum (arr, size - 1);
    
  7.    // use solution of recursive call to solve this problem
    
  8.    result = smallResult + arr[size - 1];
    
  9. }
    
  10. return result;
    
  11. }

I)I just wanted to ask that whether recursion will occur at line 7 or
at line 10 first time?

At first, the base case at line #4 will be solved for the ultimate (last) call and it will return the value 0 to line #7 of the penultimate function (second last). Then the rest of the code for the penultimate function will be completed and it will return the value to the third last function and so on…

At last,bug killed :slight_smile:
thanks!!!

@rudra_saraf >> You’re welcome buddy :slight_smile: Accept the answer and close the question. Have a nice weekend.