1

I am writing a function to return the maximum value of an array and currently it is not returning the right value.

Function:

int findMax(int maximum[ARRAY_SIZE])
{   
    int largest=maximum[0];

     for(int i=0;i<ARRAY_SIZE;i++)
    {
        if (maximum[i]>largest)
        {
          return largest=maximum[i];
        }
    }
}

Main function part:

cout<<"Maximum number: "<< findMax(numbers) <<endl;
1
  • 1
    You shouldn't return the value from within the loop but just save it. Return largest at the end. Commented Nov 5, 2015 at 14:54

3 Answers 3

2

return largest=maximum[i]; this line will make your loop return early by returning the first element found.

Probably you wanted to do just largest = maximum[i]; and then return largest; after your loop.

But you are using C++, why do you need to roll your own findMax function:

int array[] = {1,100,65,21,12,5};
int* max = ::max_element(begin(array), end(array));
Sign up to request clarification or add additional context in comments.

Comments

1

return (sort of) immediately ends the function call. What you want is to update largest and, at the end of findMax, return largest.

You may also want to read a complete C++ course and name your parameters in a more logical way.

int findMax(int data[], std::size_t size)
{   
    int largest=data[0];

    for(std::size_t i=0 ; i < size ; ++i)
    {
        if (data[i] > largest)
        {
            largest = data[i];
        }
    }

    return largest;
}

Comments

0
for(int i=0;i<ARRAY_SIZE;i++)
{
    if (maximum[i]>largest)
    {
          return largest=maximum[i];
    }
}

The loop statement will stop when a larger value is found, it may not check all elements in array. It should be modified like below:

for(int i=0;i<ARRAY_SIZE;i++)
    {
        if (maximum[i]>largest)
        {
          largest=maximum[i];
        }
    }
return largest;

Everytime you check an element in array, if it's larger than the current max value, then update max value to current element. Finally return the max value

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.