Answer to Question #188988 in C# for santhosh asrith

Question #188988

2. Write a program to define a two dimensional array of numbers to store 5 rows and 6 columns. Write a code to accept the data, assign it in array, and print the data entered by the user.


1
Expert's answer
2021-05-05T14:27:00-0400
using System;

namespace Test
{
    class Array2DTest
    {
        static int Main()
        {
            const int ROWS_COUNT    = 5;
            const int COLUMNS_COUNT = 6;

            int[,] array = new int[ROWS_COUNT, COLUMNS_COUNT];

            Console.WriteLine("Enter {0} numbers ({1} rows {2} columns each):"
                             ,ROWS_COUNT * COLUMNS_COUNT, ROWS_COUNT, COLUMNS_COUNT);

            for(int row = 0; row < ROWS_COUNT; ++row)
            {
                string   line = Console.ReadLine();
                string[] nums = line.Split();

                if(nums.Length != COLUMNS_COUNT)
                {
                    Console.WriteLine("Bad input");
                    return 1;
                }

                for(int column = 0; column < COLUMNS_COUNT; ++column)
                {
                    if(!int.TryParse(nums[column], out array[row, column]))
                    {
                        Console.WriteLine("Bad input");
                        return 1;
                    }
                }
            }

            Console.WriteLine("\nResult array:");

            for(int row = 0; row < ROWS_COUNT; ++row)
            {
                for(int column = 0; column < COLUMNS_COUNT; ++column)
                {
                    Console.Write("{0}", array[row, column]);
                    Console.Write(column < COLUMNS_COUNT - 1 ? "\t" : "\n");
                }
            }

            return 0;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS