简体   繁体   中英

How to find maximum value in an array

var max=0.0d;
for(inc=0;inc<array.length;inc++){
if(max<array[inc])
max=array[inc];
}

I want to find out the maximum value of an array.The above code is generally we used to find out maximum value of an array.

But this code will return 0 if the array contains only negative values. Because 0 < negative never become true

How to handle this conditions. Please suggest a solution.

You can try like this if you dont want to try any inbuilt functions:

int max = arr[0];
foreach (int value in arr) 
{
  if (value > max) 
  max = value;
}
Console.WriteLine(max);

IDEONE DEMO

How to handle this conditions.

You could initialize the max value as the minimum double:

var max = double.MinValue;

Alternatively you could use the .Max() LINQ extension method which will shorten your code, make it more readable and handle the case of an array consisting only of negative values:

var max = array.Max();

You can simply use Max() linq extension.

var maxvalue = array.Max();

Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM