2
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.

Venkat
  • 2,549
  • 2
  • 28
  • 61
  • 2
    `array.Max()` is not working for you? – Hari Prasad Mar 08 '16 at 06:57
  • 1
    Possible duplicate of [LINQ: How to perform .Max() on a property of all objects in a collection and return the object with maximum value](http://stackoverflow.com/questions/1101841/linq-how-to-perform-max-on-a-property-of-all-objects-in-a-collection-and-ret) – Ian Mar 08 '16 at 07:01

3 Answers3

4

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

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
3

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();
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

You can simply use Max() linq extension.

var maxvalue = array.Max();

Working Demo

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35