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.

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

2

You can simply use Max() linq extension.

var maxvalue = array.Max();

Working Demo

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.