Reputation: 2579
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.
Upvotes: 2
Views: 2826
Reputation: 172418
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);
Upvotes: 4
Reputation: 16956
You can simply use Max()
linq extension.
var maxvalue = array.Max();
Working Demo
Upvotes: 2
Reputation: 1038770
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();
Upvotes: 3