GameAtrix1
GameAtrix1

Reputation: 369

Printing a 2D-array into "squares"

I'm trying to learn how to work with 2D-array and I can't seem to understand how to print them correctly. I want to print them in a "square" like 5x5 but all I get is one line. I've tried both WriteLine and Write and changed some of the variables in the loops but I get either an error or not the result I want to have. The code is supposed to print out a 5x5 with a random sequence of 15 numbers in each column. I get the correct numbers out of it, it's only the layout that is wrong.

static void Main(string[] args)
{
    Random rnd = new Random();
    int[,] bricka = new int[5, 5];
    int num = 0;
    int num1 = 1;

    for (int i = 0; i < bricka.GetLength(1); i++)
    {
        num += 16;
        for (int j = 0; j < bricka.GetLength(0); j++)
        {
            bricka[j, i] = rnd.Next(num1, num);
        }
        num1 += 16;
    }

    for (int i = 0; i < bricka.GetLength(0); i++)
    {
        for (int j = 0; j < bricka.GetLength(1); j++)
        {
            Console.Write(bricka[i, j]+ " " );
        }
    }
    Console.ReadKey();
}

This is my print, I would like to have the the 12 under the 8 and 14 under the 12 and so on. https://i.sstatic.net/19MrT.png

Upvotes: 0

Views: 1052

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70652

You need to call WriteLine() after each line, so that each line is printed on a separate line:

for (int i = 0; i < bricka.GetLength(0); i++)
{
    for (int j = 0; j < bricka.GetLength(1); j++)
    {
        Console.Write(bricka[i, j]+ " " );
    }
    Console.WriteLine();
}

That would be one way of doing it, anyway.

Upvotes: 3

Related Questions