C# Multidimensional Arrays
In programming, we often need to work with collections of data that have multiple dimensions. While one-dimensional arrays store elements in a linear structure, multidimensional arrays allow you to organize data in a grid-like format with rows and columns (and even more dimensions). In C#, multidimensional arrays are powerful data structures that help solve complex problems.
What are Multidimensional Arrays?
A multidimensional array is an array of arrays, creating a grid-like structure with multiple dimensions. C# supports two types of multidimensional arrays:
- Rectangular Arrays - Arrays with a fixed number of rows and columns
- Jagged Arrays - Arrays of arrays, where each inner array can have a different length
Rectangular Multidimensional Arrays
Declaration and Initialization
You can declare a rectangular multidimensional array using commas inside the square brackets to specify dimensions.
// Declaration of a 2D array (without initialization)
int[,] matrix;
// Declaration and initialization of a 2D array (3 rows, 4 columns)
int[,] matrix = new int[3, 4];
// Declaration and initialization with values
int[,] matrix = new int[2, 3] {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
// Alternative syntax
int[,] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Accessing Elements
To access elements in a rectangular array, you need to specify the indices for each dimension:
// Get the element at row 0, column 1
int element = matrix[0, 1];
// Set the element at row 1, column 2
matrix[1, 2] = 42;
Example: Working with a 2D Array
Let's create a program that creates a 3×3 matrix, fills it with values, and then calculates the sum of each row:
using System;
class Program {
static void Main() {
// Create a 3x3 matrix
int[,] matrix = new int[3, 3];
// Fill the matrix with values
Console.WriteLine("Enter 9 integer values for the 3x3 matrix:");
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
Console.Write($"Enter value for position [{row},{col}]: ");
matrix[row, col] = Convert.ToInt32(Console.ReadLine());
}
}
// Display the matrix
Console.WriteLine("\nYour matrix:");
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
Console.Write(matrix[row, col] + "\t");
}
Console.WriteLine();
}
// Calculate and display the sum of each row
Console.WriteLine("\nSum of each row:");
for (int row = 0; row < 3; row++) {
int sum = 0;
for (int col = 0; col < 3; col++) {
sum += matrix[row, col];
}
Console.WriteLine($"Row {row}: {sum}");
}
}
}
Sample Input and Output:
Enter 9 integer values for the 3x3 matrix:
Enter value for position [0,0]: 1
Enter value for position [0,1]: 2
Enter value for position [0,2]: 3
Enter value for position [1,0]: 4
Enter value for position [1,1]: 5
Enter value for position [1,2]: 6
Enter value for position [2,0]: 7
Enter value for position [2,1]: 8
Enter value for position [2,2]: 9
Your matrix:
1 2 3
4 5 6
7 8 9
Sum of each row:
Row 0: 6
Row 1: 15
Row 2: 24
Useful Properties and Methods
C# provides useful methods and properties for working with multidimensional arrays:
int[,] matrix = new int[3, 4];
// Get the total number of elements
int totalElements = matrix.Length; // Returns 12 (3*4)
// Get the number of dimensions
int dimensions = matrix.Rank; // Returns 2
// Get the length of a specific dimension
int rows = matrix.GetLength(0); // Returns 3
int columns = matrix.GetLength(1); // Returns 4
Jagged Arrays (Arrays of Arrays)
Jagged arrays are arrays of arrays, where each sub-array can have a different length.
Declaration and Initialization
// Declare a jagged array (an array of arrays)
int[][] jaggedArray;
// Initialize the jagged array with 3 arrays
jaggedArray = new int[3][];
// Initialize each inner array separately
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[2]; // Second row has 2 columns
jaggedArray[2] = new int[5]; // Third row has 5 columns
// Initialize with values
int[][] jaggedArray = new int[][] {
new int[] { 1, 2, 3, 4 },
new int[] { 5, 6 },
new int[] { 7, 8, 9, 10, 11 }
};
Accessing Elements
// Accessing elements
int value = jaggedArray[0][2]; // Access the 3rd element of the 1st array
// Setting values
jaggedArray[1][1] = 42;
Example: Student Grades with Jagged Arrays
Let's create a program to store and analyze grades for different students, where each student might have a different number of grades:
using System;
class Program {
static void Main() {
// Create a jagged array for 3 students with varying numbers of grades
Console.WriteLine("Enter grades for 3 students:");
int[][] studentGrades = new int[3][];
for (int student = 0; student < 3; student++) {
Console.Write($"How many grades for student {student + 1}? ");
int gradeCount = Convert.ToInt32(Console.ReadLine());
studentGrades[student] = new int[gradeCount];
for (int grade = 0; grade < gradeCount; grade++) {
Console.Write($"Enter grade {grade + 1} for student {student + 1}: ");
studentGrades[student][grade] = Convert.ToInt32(Console.ReadLine());
}
}
// Calculate and display average grade for each student
Console.WriteLine("\nStudent Grade Report:");
for (int student = 0; student < studentGrades.Length; student++) {
int sum = 0;
foreach (int grade in studentGrades[student]) {
sum += grade;
}
double average = (double)sum / studentGrades[student].Length;
Console.WriteLine($"Student {student + 1} - Grades: {string.Join(", ", studentGrades[student])}");
Console.WriteLine($"Student {student + 1} - Average: {average:F2}");
Console.WriteLine();
}
}
}
Sample Input and Output:
Enter grades for 3 students:
How many grades for student 1? 3
Enter grade 1 for student 1: 85
Enter grade 2 for student 1: 90
Enter grade 3 for student 1: 95
How many grades for student 2? 2
Enter grade 1 for student 2: 75
Enter grade 2 for student 2: 80
How many grades for student 3? 4
Enter grade 1 for student 3: 92
Enter grade 2 for student 3: 88
Enter grade 3 for student 3: 76
Enter grade 4 for student 3: 94
Student Grade Report:
Student 1 - Grades: 85, 90, 95
Student 1 - Average: 90.00
Student 2 - Grades: 75, 80
Student 2 - Average: 77.50
Student 3 - Grades: 92, 88, 76, 94
Student 3 - Average: 87.50
Three-Dimensional Arrays and Beyond
C# supports arrays with three or more dimensions. These are less common but can be useful in specific scenarios like 3D modeling, scientific simulations, or video game development.
// 3D array (2x3x4) - 2 "layers", each with 3 rows and 4 columns
int[,,] threeDArray = new int[2, 3, 4];
// Initialize a value
threeDArray[0, 1, 2] = 42;
// Initialize a 3D array with values
int[,,] threeDArray = new int[2, 2, 3] {
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } }
};
Real-World Application: Simple Game Board
Let's create a simple tic-tac-toe game board using a 2D array:
using System;
class TicTacToe {
static void Main() {
// Create a 3x3 tic-tac-toe board
char[,] board = new char[3, 3] {
{ ' ', ' ', ' ' },
{ ' ', ' ', ' ' },
{ ' ', ' ', ' ' }
};
// Make some moves
board[0, 0] = 'X';
board[1, 1] = 'O';
board[0, 2] = 'X';
// Display the board
Console.WriteLine("Tic-Tac-Toe Board:");
Console.WriteLine();
for (int row = 0; row < 3; row++) {
Console.Write(" ");
for (int col = 0; col < 3; col++) {
Console.Write(board[row, col]);
if (col < 2) Console.Write(" | ");
}
Console.WriteLine();
if (row < 2) {
Console.WriteLine("---+---+---");
}
}
}
}
Output:
Tic-Tac-Toe Board:
X | | X
---+---+---
| O |
---+---+---
| |
When to Use Each Type of Array
-
Rectangular Arrays: Use when you need a grid with the same number of columns in each row.
- Examples: Chess/checkerboard, pixel data, spreadsheet data
-
Jagged Arrays: Use when you have collections of varying sizes.
- Examples: Student grades, irregular data structures, optimization for sparse matrices
Performance Considerations
- Rectangular arrays (
int[,]
) have slightly better performance for accessing elements because they're stored in a continuous block of memory - Jagged arrays (
int[][]
) offer more flexibility and can be more memory-efficient when your data has irregular dimensions
Summary
Multidimensional arrays in C# provide powerful tools for organizing and manipulating complex data structures:
- Rectangular arrays use the
[,]
syntax and have a fixed number of elements in each dimension - Jagged arrays use the
[][]
syntax and can have varying lengths for inner arrays - Use array properties like
Length
,Rank
, andGetLength()
to work with dimensions - Choose the appropriate type based on your data structure needs
Exercises
-
Create a program that initializes a 3×3 matrix with random numbers between 1-100, then finds and displays the largest number along with its position.
-
Implement a program that creates a multiplication table as a 10×10 matrix and displays it in a formatted grid.
-
Create a program that simulates a seating chart for a theater using a 2D array, where each cell represents a seat that can be either available ('A') or sold ('S').
-
Implement a jagged array to represent a collection of test scores for different subjects, where each subject might have a different number of tests. Calculate the average for each subject.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)