-1

Running perfect but there is no result only cursor. The expected result is -15

        int[] dizi = { 4, 5, -15, 22, -34, 3, 0, 7, 43, 100 };
        int maxNumber = 0;

        for (int i = 0; i < dizi.Length; i++)
        {
            if (dizi[i] < 0)
            {
                if (maxNumber < dizi[i])
                {
                    maxNumber = dizi[i];
                    Console.WriteLine(maxNumber);
                }
            }
        }
        Console.ReadKey();
fubo
  • 44,811
  • 17
  • 103
  • 137

6 Answers6

7

You can use Where and Max extension methods from System.Linq namespace:

var maxNegative = dizi.Where(x => x < 0).Max(); 
Console.WriteLine(maxNegative);

Max() will throw exception if there is not any negative number in the collection. So, you may want to use DefaultIfEmpty if you want to return 0 instead of any exception:

var maxNegative = dizi.Where(x => x < 0)
        .DefaultIfEmpty()
        .Max(); 
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
  • @AnektarcıLegend Actually, this is not a big deal. But, of course it might be better to write your own code in the beginning rather than using Linq methods – Farhad Jabiyev Sep 14 '16 at 12:39
  • 1
    +1 for `.DefaultIfEmpty()` mentioning. Extreme cases (no negative numbers in this particular code) are worth considering. – Dmitry Bychenko Sep 14 '16 at 12:42
3

Use Max() to determine your desired value

int[] dizi = { 4, 5, -15, 22, -34, 3, 0, 7, 43, 100 };
int result = dizi.Where(x => x < 0).Max();

If you want to keep your code, replace int maxNumber = 0; with int maxNumber = int.MinValue; so maxNumber gets overwritten, otherwise there can't be a bigger negative number compared to 0

fubo
  • 44,811
  • 17
  • 103
  • 137
0

You can try this:

int maxNumber = 0;
    for (int i = 0; i < dizi.length; i++) {
        if (dizi[i] < 0) {
            if (maxNumber == 0 || dizi[i] > maxNumber ) {
                maxNumber = dizi[i];
            }
        }
    }
return maxNumber;

IDEONE DEMO

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

If you are looking for non-Linq solution (good old loop):

    int[] dizi = { 4, 5, -15, 22, -34, 3, 0, 7, 43, 100 };
    int maxNumber = 0;

    foreach (var item in dizi)
      if ((item < 0) && (maxNumber == 0 || item > maxNumber))
        maxNumber = item;

    Console.WriteLine(maxNumber);
    Console.ReadKey();

This code either prints out the maximum negative number -15 or 0 if the coolection (dizi) doesn't contain any negative numbers

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

i realize if maxNumber lower than any array elements for example int maxNumber=-100 program works too

0

Replace your code with this and you will get the correct output

   max=0;
   while(i<dizi.Length)
   {
      if(dizi[i]<max)
       max=dizi[i];
      i++;
   }
   if(max!=0)
   {
      Console.WriteLine(max);
   }
   else Console.WriteLine("No negative number")
 }