Notifications
Clear all
Topic starter 01/08/2025 11:48 pm
In C#, arrays are used to store fixed-size collections of elements of the same data type—like a shelf lined with boxes where each box holds a single item.
🏗️ Declaring and Initializing Arrays
- Declare with a specific size:
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
- Inline initialization:
string[] fruits = { "Apple", "Banana", "Cherry" };
🔍 Accessing Elements
- Arrays use zero-based indexing:
Console.WriteLine(fruits[1]); // Output: Banana
🔄 Looping Through Arrays
- Using
foreach
:
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
- Or using
for
:
for (int i = 0; i < fruits.Length; i++)
{
Console.WriteLine(fruits[i]);
}
🧠 Array Properties & Methods
Length
gives the number of elements- Use
Array.Sort()
to sort - Use
Array.IndexOf()
to search
Array.Sort(fruits);
int index = Array.IndexOf(fruits, "Cherry");
🧬 Multidimensional & Jagged Arrays
- 2D Array (Matrix style):
int[,] grid = new int[2, 3];
grid[0, 1] = 42;
- Jagged Array (Array of arrays):
int[][] jagged = new int[2][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };