Ivica Čevis
Ivica Čevis

Reputation: 33

C# 2D Array - how to print the largest element in each row

I'm raeding MTA 98-361 and there is a task: You are writing a program that uses a two-dimensional array. The array has four rows and five columns. You need to print the largest element in each row of the array.

My code:

  static void Main(string[] args)
  {
      //[x, y] row, col
     int[,] grid = new int[4,5] { { 1, 2, 4,  5,  6 }, //how to get largest number of each row
                                  { 3, 4, 7,  8,  9 }, 
                                  { 5, 6, 56, 12, 45 }, 
                                  { 7, 8, 45, 12, 78 }};

     for (int row = 0; row < grid.GetLength(0); row++)
     {
        for (int col = 0; col < grid.GetLength(1); col++)
        {
           Console.Write(grid[row, col] + "\t ");
        }
        Console.WriteLine();
     }
     Console.WriteLine("Row1: {0} {1} {2} {3} {4} ", grid[0, 0], grid[0, 1], grid[0, 2], grid[0, 3], grid[0, 4]);

     Console.ReadLine();
  } 

I know that this is my task, and should solve it, but I'm stuck. Can you give me advice how to accomplish it?

Thanks!

Upvotes: 2

Views: 1771

Answers (1)

Blindy
Blindy

Reputation: 67417

Here's how you do it without spawning threads:

public static void Main()
{
     int[,] grid = new int[4,5] { { 1, 2, 4,  5,  6 }, //how to get largest number of each row
                                  { 3, 4, 7,  8,  9 }, 
                                  { 5, 6, 56, 12, 45 }, 
                                  { 7, 8, 45, 12, 78 }};

    int w=grid.GetLength(0), h=grid.GetLength(1);
    Console.WriteLine(string.Join(",",
        Enumerable.Range(0,w).Select(i=>Enumerable.Range(0,h).Select(j=>grid[i,j]).Max())));
}

You can see it in action here: https://dotnetfiddle.net/8u08i3

Upvotes: 4

Related Questions