0

Consider the function

void solve(int arr[],int ind,int sum,int n,int count)
{
    if(ind==n){
          if(sum>max)
              max=sum;
      }
      else{
          sum+=arr[ind];//sum
          if(ind==n-1)
            solve(arr,ind+1,sum,n,1);//1st call
          if(ind==n-2 && count>1)
            solve(arr,ind+2,sum,n,1);//2nd call
          if(ind<n-1 && count<2){
              count++;
              solve(arr,ind+1,sum,n,count);//3rd call
          }
          if(ind<n-2)
              solve(arr,ind+2,sum,n,1);//4th call
          if(ind<n-3)
              solve(arr,ind+3,sum,n,1);//5th call
      }
}

I have no problem about the logic but am confused about the passing of the variables.I am not able to make out whether the integer sum+=arr[ind] //sum is passed as the same variable in every call or is it updated after every call of the function?

2
  • Thnx..I got the answer I gues...but @user3386109 what do you mean by c++ answer....is it different in c? Commented Jul 23, 2016 at 4:11
  • 1
    References are a C++ feature. In C, you would use a pointer. Commented Jul 23, 2016 at 4:11

2 Answers 2

2

sum is passed by value, so the value won't be updated. The following 5 solve calls will be passed with the same sum value.

If you want sum to be updated after each call, you should pass it by reference: void solve(int arr[],int ind,int &sum,int n,int count)

Sign up to request clarification or add additional context in comments.

Comments

1

The value of sum is updated but locally everytime the function solve gets called.You can visualize this by printing the value of sum inside the function definition.

See the below example.

#include <stdio.h>
void call(int);
int main(void) {
    // your code goes here
    call(5);
    return 0;
}
void call(int sum)
{
    if(sum>15)
      return;
    printf("%d ",sum);
    sum+=5;
    call(sum);

}

The o/p is 5 10 15 .

May be this helps you to visualize more clearly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.