Home  • Courses • Software Engineering

C#.NET Array

Declaring Array
//1D array
string[] names = { "Tabina", "Jahid","Rasel","Tawhid" };
foreach (string name in names)
{
    Console.WriteLine(name);
}

//2D array
int[,] nums = { { 1, 4, 2 }, { 3, 6, 8 } };
Console.WriteLine(nums[0, 2]);  // Outputs 2


//loop through
int[,] numbers = { { 1, 4, 2 }, { 3, 6, 8 } };

for (int i = 0; i < numbers.GetLength(0); i++)
{
    for (int j = 0; j < numbers.GetLength(1); j++)
    {
        Console.Write(numbers[i, j]);
    }
    Console.WriteLine();
}


//

// single-dimension jagged array
int[][] c =
[
    [1,2,3,4],
    [5,6,7,8]
];
// Looping through the outer array
for (int k = 0; k < c.Length; k++)
{
    // Looping through each inner array
    for (int j = 0; j < c[k].Length; j++)
    {
        // Accessing each element and printing it to the console
        Console.WriteLine($"Element at c[{k}][{j}] is: {c[k][j]}");
    }
}


// jagged array of strings
string[][] d =
[
    ["Luca", "Mads", "Luke", "Dinesh"],
    ["Karen", "Suma", "Frances"]
];

// Looping through the outer array
int i = 0;
foreach (var subArray in d)
{
    // Looping through each inner array
    int j = 0;
    foreach (var element in subArray)
    {
        // Accessing each element and printing it to the console
        Console.WriteLine($"Element at d[{i}][{j}] is: {element}");
        j++;
    }
    i++;
}

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd