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.
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;
}
}
}
Comments
Leave a comment