Home > OS >  How do I output values from a 2D array in a table using C#
How do I output values from a 2D array in a table using C#

Time:10-24

I need to get my code to output the same table as the example output.

The code first asks for a users inputs and then stores them in an array. Data is also validated upon entry. the months range from January to December and are meant to output all results in a table like the one in the desired output.

My code:

string[] salesReps = { "Dave", "Sarah", "Juan", "Gilno" };
string[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", 
"Oct", "Nov", "Dec" };
int[,] salesStats = new int[4, 12];

//title
Console.Write("\n\nSales Figures\n");
Console.Write("*******************\n");

//sales
for (int i = 0; i < 4; i  )
{
    Console.Write("\n");
    Console.WriteLine("Enter the sales data for {0}", salesReps[i]);
    for (int j = 0; j < 12; j  )
    {
        Console.Write(months[j]   ": ");
        //validates entry
        while (!int.TryParse(Console.ReadLine(), out salesStats[i, j]))
        {
            Console.Beep();
            Console.WriteLine("Please enter only valid numbers!");
            Console.Write(months[j]   ": ");
        }
    }
}

With the code I already have how would I achieve the desired output?

Desired output:

Desired example output.

CodePudding user response:

You can use this fragment of code after //sales for loop:

Console.WriteLine("\nResult:\n");
Console.WriteLine("\t"   string.Join("\t", months)); // Print months row
StringBuilder sb = new StringBuilder();

for (int i = 0; i < salesReps.Length; i  )
{
    sb.Append(salesReps[i]   "\t"); // Add Name
    for (int j = 0; j < salesStats.Length / salesReps.Length; j  )
        sb.Append(salesStats[i, j]   "\t"); // Add values per montth

    Console.WriteLine(sb.ToString()); // Print to console
    sb.Clear(); // Clear for new row data
}

It uses StringBuilder class to build rows with \t indents for each value of salesStats. To make things up without StringBuilder usage, replace sb.Append(...) with Console.Write(...) and leave only empty Console.WriteLine() at end of first loop:

for (int i = 0; i < salesReps.Length; i  )
{
    Console.Write(salesReps[i]   "\t"); // Print Name
    for (int j = 0; j < salesStats.Length / salesReps.Length; j  )
        Console.Write(salesStats[i, j]   "\t"); // Print values per month at same line in Console

    Console.WriteLine(); // To make line break
}

You can "play" with .PadLeft(int) value to align items as you wish. I mean for example:

salesReps[i].PadLeft(3)   "\t";
salesStats[i, j].ToString().PadLeft(3)   "\t";

3 in that case should be length of max j value in string representation, I think (e.g. "4321" - length=4, "78923" - length=5 etc). You can search StackOverflow about how get Max value of in multidimensional array. One of them here.

  • Related