Reputation: 1145
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?
Upvotes: 0
Views: 63
Reputation: 2001
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.
Upvotes: 1
Reputation: 22936
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)
Upvotes: 2