0 day streak
csharp / intermediate
Snippet

Array Summation with Local Recursive Functions

This snippet demonstrates the use of local functions within a method to perform operations on a multi-dimensional array. Local functions are useful for encapsulation and can access variables from the outer scope, such as the 'sum' variable here.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int SumMatrix(int[,] matrix)
{
int sum = 0;
void ProcessElement(int row, int col)
{
if (row >= matrix.GetLength(0)) return;
sum += matrix[row, col];
if (col + 1 < matrix.GetLength(1))
ProcessElement(row, col + 1);
else
ProcessElement(row + 1, 0);
}
ProcessElement(0, 0);
return sum;
}
Breakdown
1
int[,] matrix
Declares a 2D rectangular array parameter.
2
void ProcessElement(int row, int col)
Defines a local function that can access variables in the parent method.
3
matrix.GetLength(0)
Retrieves the length of the first dimension (rows) of the array.