Search code examples
c#arraysgridlabelconsole-application

How to do string labels for numerical array in C#?


I am trying to make a 2d array that displays the numbers with the horizontal and vertical labels above and to the left, respectively. So something like this:

The output I'm trying to get

The image attached here is the output I'm currently getting.

I created two different 1D arrays to accompany my 2D numerical grid, in order to act as the labels. However, I'm unable to get it to format in any comprehensive way, despite my attempts to change the order in which these arrays appear, adding spaces, and altering the code inside. I tried all sorts of different ways of formatting this, but I just can't figure it out. Here is the mess of code I currently have:

public int[,] GetWeeklyAttendance()
{
    string[] timeLabels =
        {"1 PM ", "3 PM ", "5 PM ", "7 PM"};
    string[] dayOfWeekLabels =
        {"Monday\n", "Tuesday\n", "Wednesday\n", "Thursday\n", "Friday\n", "Saturday\n"};
    int[,] weeklyAttendance =
    {
        {8, 10, 15, 20 },
        {11, 15, 17, 18 },
        {14, 12, 22, 20 },
        {9, 14, 17, 12 },
        {10, 12, 21, 22 },
        {12, 12, 7, 15 }
    };

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

    return weeklyAttendance;
}

Solution

  • you could use this code, a little bit of adjustment would be required.

    Console.Write(" ");
    for (int i = 0; i < timeLabels.Length; i++)
    { 
        Console.Write(timeLabels[i] + " "); 
    }
    Console.WriteLine();
    for (int i = 0; i < weeklyAttendance.GetLength(0); i++)
    {
        Console.Write(dayOfWeekLabels[i].Substring(0, dayOfWeekLabels[i].Length -1));
        for (int j = 0; j < weeklyAttendance.GetLength(1); j++)
        {
            Console.Write(weeklyAttendance[i, j] + " ");
        }
        Console.WriteLine();
    }
    

    So the concept is to first print the timeLabels items. then in a single loop only dayOfWeekLabels items row wise and print the attendance in inner for loop

    enter image description here