Showing posts with label C# Console Programming. Show all posts

Multidimensional Arrays (C# Programming Guide)


// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };
// The same array with dimensions specified.
int[, ,] array3Da = new int[2, 2, 3] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
                                       { { 7, 8, 9 }, { 10, 11, 12 } } };

// Accessing array elements.
System.Console.WriteLine(array2D[0, 0]);
System.Console.WriteLine(array2D[0, 1]);
System.Console.WriteLine(array2D[1, 0]);
System.Console.WriteLine(array2D[1, 1]);
System.Console.WriteLine(array2D[3, 0]);
System.Console.WriteLine(array2Db[1, 0]);
System.Console.WriteLine(array3Da[1, 0, 1]);
System.Console.WriteLine(array3D[1, 1, 2]);

// Output:
// 1
// 2
// 3
// 4
// 7
// three
// 8
// 12


You also can initialize the array without specifying the rank.
int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };


If you choose to declare an array variable without initialization, you must use the new operator to assign an array to the variable. The use of new is shown in the following example.
int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

Check the entered year is Leap year or not in c# console


open a console application project in c# language in your editor and just paste the following code in your class's brackets -

static void Main(string[] args)
{
try
{
Console.Write("Please Enter the Year: ");
int year = int.Parse(Console.ReadLine());
if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
{ Console.WriteLine("The year {0}, is a Leap Year", year);
}
else
{
Console.WriteLine("The year {0}, is not a Leap Year", year);
} }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine(); }

Output is-

Create a Pyramid in C# Console


open a console application project in c# language in your editor and just paste the following code in your class's brackets -

static void Main(string[] args)
{

for (int i = 0; i < k =" i;" j =" 2"> 0; j--)
{
Console.Write("*"); }
Console.WriteLine("");
}
Console.ReadLine();
}

Output is-