0
using namespace std;


int A[]={1,3,4};

int max(int A[], int n){
    if(n==1) return A[0];
    int res = max(A,n-1);
    if(res>A[n-1]) return res;
    else return A[n-1];

}
int main(){
    cout<<max(A,3);
}

the code works but what i dont understand is how res can take another value except A[0]. Everytime i trace it i can not understand how max(A,n-1) can have a result except when n=1

  • Suggested reading: [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Stef May 27 '21 at 11:34

2 Answers2

0

It is because of this condition if(res>A[n-1]) return res. res takes A[0] only on the last step of the recursion, when this step returns, the above mentioned if condition of the remaining recursive calls gets executed in Last In First Out order, and res varies accordingly.

Charchit Kapoor
  • 8,934
  • 2
  • 8
  • 24
0

the code works but what i dont understand is how res can take another value except A[0]. Everytime i trace it i can not understand how max(A,n-1) can have a result except when n=1

your recursion will first call max(...) with the array and n and n is decreasing until n==1 and you return A[0] then on each time you return from inner call you compare the return value from inner call and the current value

so actually you compare A[0] to A[1] , the max between them with A[2] etc ..

   if(res>A[n-1]) return res;
    else return A[n-1];
RDF
  • 51
  • 8