• Status: Solved
• Priority: Medium
• Security: Public
• Views: 235

# Program that Displays the Max of an Array

I have a homework assignment which is to write a function that takes an array of floats and the length of
the array, and returns the maximum value in the array.  So far I have tried a few different things and what I have finally settled on is something as seen below.  The problem is that I realized I will need thousands of if statements to say if n10> n9>n8...and use all combinations possible to get the max displayed.  Is there an easier way to do this or did I start off completely wrong?

{
printf("Enter up to 10 decimal values: "); /*Asks the user for values to find\
the maximum of*/

fgets(line, sizeof(line), stdin); /*Reads the line of floats given*/

sscanf(line, "%f %f %f %f %f %f %f %f %f %f", &n1, &n2, &n3, &n4, &n5, &n6, &\
n7, &n8, &n9, &n10); /*Converts the string into numbers*/

/*Here is where I need to define the arraymax function, but I don't know how*\
/

for (i=1; i<11; i++)
{
A[i] = (float);
}

printf("The arrayMax function returned %f\n", answer);

return 0;
}

0
spngegirl01
1 Solution

Commented:
You dont have to compare each value with every other value.
If A>B and A>C then you dont need to compare B and C.

Keep a variable max. Initialize it to first value in the array.
Loop through all the items in the array. If current value > max then update max to current value. At the end of the iteration you will have the max value - the utility of loops :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.