← Back to Tutorials Chapter 3

Arrays

Array Basics

Arrays store multiple values of the same type in a fixed-size collection.

int[] numbers = new int[5];
int[] scores = { 95, 87, 92, 78, 88 };
string[] names = new string[] { "Alice", "Bob", "Charlie" };

Accessing & Modifying

int first = scores[0];
scores[1] = 90;
int length = scores.Length;

Iterating

// For loop
for (int i = 0; i < scores.Length; i++) {
    Console.WriteLine(scores[i]);
}

// Foreach loop
foreach (int score in scores) {
    Console.WriteLine(score);
}

Multi-Dimensional Arrays

// Rectangular
int[,] matrix = { { 1, 2 }, { 3, 4 } };
int val = matrix[0, 1];

// Jagged (array of arrays)
int[][] jagged = new int[3][];
jagged[0] = new int[] { 1, 2 };
jagged[1] = new int[] { 3, 4, 5 };

Array Class Methods

Array.Sort(scores);
Array.Reverse(scores);
int index = Array.IndexOf(scores, 92);
Array.Clear(scores, 0, scores.Length);
C# array structure

Practice Task

Write a C# program that applies the concepts covered in this chapter. Experiment with different inputs and test your understanding.