Answer:
I wrote this program using C# and Visual Studio. This program requires to display 2D array which has 4 rows and 5 columns. it is also noted that, this program requires to display first and third row in ascending order while second and fourth row in descending order.
To iterate through each row for loop is used and inside for loop, switch statement is used to decide on first, second, third and fourth row that is which rows should be displayed in ascending orders, and which are required to display in descending orders.
Explanation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2D_Array
{
class Program
{
static void Main(string[] args)
{
int[,] a = new int[4, 5]{
{1, 2, 3,4,5} , /* initializers for row indexed by 0 */
{6, 7,8,9,10} , /* initializers for row indexed by 1 */
{11,12,13,14,15},/* initializers for row indexed by 2 */
{ 16,17,18,19,20},/* initializers for row indexed by 3 */
};
for (int row = 0; row < 4; row++)// here we iterate through each row and display the result
{
switch (row)//the purpose of using switch statement is that, we will display first and 3rd row in ascending order while 2nd and 5th row in descending order
{
case 0:// here to display row 1
{
for (int i = 0; i < 1; i++)
{
Console.Write("[");
for (int j = 0; j < 5; j++)
Console.Write(a[i, j]+ (j >3 ? "" : ","));
}
Console.Write("]");
Console.WriteLine();
}
break;
case 1://here to display row two
{
for (int i = 1; i < 2; i++)
{
//Console.WriteLine("row 1");
Console.Write("[");
for (int j = 4; j >= 0; j--)// to display array elements in reverse order
{
Console.Write(a[i, j] + (j == 0 ? "" : ","));
}
}
Console.Write("]");
Console.ReadLine();
break;
}
case 2://here to display the 3rd row
{
for (int i = 2; i < 3; i++)
{
Console.Write("[");
for (int j = 0; j <5; j++)
{
Console.Write(a[i, j] + (j > 3 ? "" : ","));
}
}
Console.Write("]");
Console.ReadLine();
}
break;
case 3://here to display 4th row.
{
for (int i = 3; i < 4; i++)
{
//Console.WriteLine("row 1");
Console.Write("[");
for (int j = 4; j >= 0; j--)
{
Console.Write(a[i, j] + (j == 0 ? "" : ","));
}
Console.Write("]");
}
Console.ReadLine();
}
break;
}
}
}
}
}