Finding the maximum element of an array recursively

后端 未结 5 2073
遥遥无期
遥遥无期 2020-12-20 19:08

Consider this code, which computes the maximum element of an array.

#include 

int maximum(int arr[], int n)
{
    if (n == 1) {
        retur         


        
5条回答
  •  忘掉有多难
    2020-12-20 19:22

    That is what it is coded to do...

    Take a look:

    from main we call maximum with 5, then in the else we call the function again with n-1.

    maximum(array, 5)  //first call from main, hit the else n=5, so recall with n-1
    maximum(ar, 4)     //second call from maximum, hit the else n=4, so recall with n-1
    maximum(ar, 3)     //third call from maximum, hit the else n=3, so recall with n-1
    maximum(ar, 2)     //fourth call from maximum, hit the else n=2, so recall with n-1
    maximum(ar, 1)     //fifth call from maximum, n==1 now so do the if and return 5
    

提交回复
热议问题