1
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,398
  • 2
  • 20
  • 51
  • 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
  • 152,732
  • 28
  • 233
  • 299
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
  • 960,118
  • 257
  • 3,196
  • 2,876
1

You can simply use Max() linq extension.

var maxvalue = array.Max();

Working Demo

Hari Prasad
  • 15,659
  • 4
  • 18
  • 33