Search code examples
c#loopstabular

C# using loops to generate a table with correct arithmetic relationship


The following is the ShowTab() method, how to apply dynamic numbers and result in to the table?

using System;


const int MAX = 4;
int cage = 500/total;

int month = 1; 
int adults = 1; 
int babies = 0;
int total  = 1;

Console.WriteLine("Month\tAdults\tBabies\tTotal");
Console.WriteLine("{0, -10}{1, -10}{2, -10}{3, -10}", month, adults, babies, total);

for(int i = 0; i < MAX; i++) {
Console.writeLine(  
}

Solution

  • Maybe I missed something ; but if it's only about formatting somehow ; something like this should do the job :

    int month = 1;
    int adults = 1;
    int babies = 0;
    int total = 1;
    
    Console.WriteLine ("header row"); // optional (if needed)
    
    while (/* there is still cages to hold them */)
    {
        // print current state (-10 width chosen for example, negative for left align)
        Console.WriteLine ($"{month, -10}{adults, -10}{babies, -10}{total, -10}");
    
        // do the maths to update values
        month = /* ... */;
        adults = /* ... */;
        babies = /* ... */;
        total = /* ... */;
    }
    

    Here is a dummy exemple which illustrate why I choose to use width formatting specifier rather than tabulation (as hinted in one comment link).