0% found this document useful (0 votes)
2 views

Lab1.6 Array

d

Uploaded by

karantestingdemo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab1.6 Array

d

Uploaded by

karantestingdemo
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Array Examples :

public class ArrayExamples


{

// Main Method
public void ArrayFirstExamples()
{

// declares an Array of integers.


int[] intArray;

// allocating memory for 5 integers.


intArray = new int[5];

// initialize the first elements


// of the array
intArray[0] = 10;

// initialize the second elements


// of the array
intArray[1] = 20;

// so on...
intArray[2] = 30;
intArray[3] = 40;
intArray[4] = 50;

// accessing the elements


// using for loop
Console.Write("For loop :");
for (int i = 0; i < intArray.Length; i++)
Console.Write(" " + intArray[i]);

Console.WriteLine("");
Console.Write("For-each loop :");

// using for-each loop


foreach (int i in intArray)
Console.Write(" " + i);

Console.WriteLine("");
Console.Write("while loop :");
// using while loop
int j = 0;
while (j < intArray.Length)
{
Console.Write(" " + intArray[j]);
j++;
}

Console.WriteLine("");
Console.Write("Do-while loop :");

// using do-while loop


int k = 0;
do
{
Console.Write(" " + intArray[k]);
k++;
} while (k < intArray.Length);
}
}
What Is Multidimensional C# Arrays?

The multidimensional array has multiple rows for storing values. It is also known as a
Rectangular C# Array. It can be a 2D, 3D, or more array. A nested loop was required to
store and access the array's values. Therefore, you must use commas inside the square
brackets to create a multidimensional array.

Now, create a two-dimensional array using code.

Code:

public void MultiArrayExamples()

int[,] array = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

for (int i = 0; i < 3; i++)

{
for (int j = 0; j < 3; j++)

Console.WriteLine(array[i, j] + " ");

Console.WriteLine();

What Are Jagged C# Arrays?


A jagged array in C# is called an "array of arrays" in C# since each element is an array. A
jagged array's element size might vary.

public void JaggedArrayExamples()

int[][] array = new int[2][]; //definition of array

array[0] = new int[6] { 42, 61, 37, 41, 59, 63 };

array[1] = new int[4] { 11, 21, 56, 78 };

for (int i = 0; i < array.Length; i++)


{

for (int j = 0; j < array[i].Length; j++)

System.Console.Write(array[i][j] + " ");

System.Console.WriteLine();

You might also like