0

hello everyone I'm puzzled why this function returns 0 every time. I use arr[0] as index and define it size of array in main func.

int sum_array (int arr[]) {
    int result;
    arr[0] = arr[0]-1;
    if(arr[0]<=0){
        return 0;
    }
    result = ((sum_array(arr))+(arr[arr[0]]));
    return result;


} 

If I use if(arr[0]<=1) instead of if(arr[0]<=0) it returns 5. I also don't get why it returns 5.

array = {0,1,1,2,3,3,4}
4
  • 1
    The line result=((sum_array(arr))+(arr[arr[0]])); exhibits undefined behaviour because the result is dependant on the evaulation order of + as the left side modifies arr[0] and the right side reads the same value. Your program is ill-formed. Therefore the compiler is under no obligation to output anything sensible. Commented Apr 26, 2020 at 23:43
  • Thanks bro. it helped a lot <3 Commented Apr 26, 2020 at 23:47
  • ... also, the line mentioned above is practically unreachable with your array input because the if statement will be true in the first call and any subsequent call as well. Commented Apr 26, 2020 at 23:50
  • of course, if you don't post the code in main.... or you don' t say what do you pass as the arrary parameter, it's impossible to guess what is even the purpose of your routine. Please, have a look at this page Commented Apr 29, 2020 at 13:37

1 Answer 1

1

the following proposed code:

  1. uses recursion
  2. performs the desired functionality

and now, the proposed code:

int sum_array (int arr[]) 
{
    if(arr[0]<=0)
    {
        return 0;
    }
    else
    {
        int index = arr[0];
        arr[0]--;
        return arr[ index ] + sum_array( arr );
    }
}
Sign up to request clarification or add additional context in comments.

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.