Search code examples
c#console

Printing the Given numbers in given columns and rows Console Application


I want to print the given list according to the number of rows and columns but displaying frist 6 numbers all the time

static void Main(string[] args)
    {
        //string total, rows, columns = "";
        //Console.WriteLine("Enter Total No Of Numbers");
        //total = Console.ReadLine();
        //Console.WriteLine("Enter all Numbers seperated by Comma");
        //var allNumbers = Console.ReadLine();
        //var array = allNumbers.Split(',');
        //Console.WriteLine("Enter Number of Rows");
        //rows = Console.ReadLine();
        //Console.WriteLine("Enter Number of columns");
        //columns = Console.ReadLine();

        string total, rows, columns = "";

        total = "30";
        var allNumbers = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";
        var array = allNumbers.Split(',');

        rows = "5";

        columns = "6";

        for (int i = 0; i < Convert.ToInt32(rows); i++)
        {
            for (int j = 0; j < Convert.ToInt32(columns); j++)
            {
                Console.Write(array[j]);
                Console.Write("\t");
            }

            Console.WriteLine();
        }
        Console.ReadLine();
    }

Solution

  • Here you go:

    string total, rows, columns = "";
    
    total = "30";
    var allNumbers = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";
    var array = allNumbers.Split(',');
    
    rows = "5";
    
    columns = "6";
    
    for (int i = 0; i < Convert.ToInt32(rows); i++)
    {
        for (int j = 0; j < Convert.ToInt32(columns); j++)
        {
            Console.Write(array[j + (i * Convert.ToInt32(columns))]);
            Console.Write("\t");
        }
    
        Console.WriteLine();
    }
    

    Basically in your loop, you never tried to move past the first row index-wise. Some comments that I feel need to be made:

    1. Use variables to store results of parsing your input.
    2. Prefer to use int.TryParse(...) that Convert (depending on your situation). While both work, with TryParse allows more fine-grained control of errors.
    3. Loops inside loops are a bad idea (if you can avoid them). You could use a single loop for this purpose, doing a Console.WriteLine when you reached the end of a row, and you would not have hit this issue.