110-c-sharp-array-and-multidimensional-array-example

C sharp array is different in defining from array in C programming language.

Array in C program would go like this:

int a[10];

C sharp array example in here would be used together with for loop to write “Hello World!” message.

char[] array = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘!’ };
for (int int_i = 0; int_i < array.Length; int_i++)
{

Console.Write(array[int_i]);

}
Property Length goes automatically with array. So initial complexity in defining array in C#, now has it’s benefit for automatic obtaining array length.

Another example is c sharp multidimensional array and it goes like this:

double[,] matrix = new double[5, 5];
for (int int_i = 0; int_i < 5; int_i++)
{

for (int int_j = 0; int_j < 5; int_j++)
{

matrix[int_i,int_j] = ((double)int_i*(double)int_j)/10.0;
matrix[int_i, int_j] += (double)int_i + (double)int_j;
Console.Write(matrix[int_i, int_j].ToString(“#0.00″) + ” “);

}

Console.WriteLine();

}

If we want to have formatted data to be displayed, we can use method for formatting data into particular string:

ToString(“#0.00”) i.e
Console.Write(matrix[int_i, int_j].ToString(“#0.00”) + ” “);

In previous example, casting data is used in the very same way as in C language, with casting operator
matrix[int_i,int_j] = ((double)int_i*(double)int_j)/10.0;

Here is the whole program:

static void Main(string[] args)
{

char[] array = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘!’ };
for (int int_i = 0; int_i < array.Length; int_i++)
{

Console.Write(array[int_i]);

}

Console.WriteLine();
Console.WriteLine();
double[,] matrix = new double[5, 5];
for (int int_i = 0; int_i < 5; int_i++)
{

for (int int_j = 0; int_j < 5; int_j++)
{

matrix[int_i,int_j] = ((double)int_i*(double)int_j)/10.0;
matrix[int_i, int_j] += (double)int_i + (double)int_j;
Console.Write(matrix[int_i, int_j].ToString(“#0.00″) + ” “);

}

Console.WriteLine();
}

}

Result of the program is displayed in figure bellow.

array_example

External links:

C Sharp Array Example on Microsoft
C Sharp Array Example on tutorialspoint
C Sharp Array Example on c-sharpcorner

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*