C# Multidimensional Arrays
C# Multidimensional Arrays
As discussed in the previous chapter, Arrays in C# will support multi-dimensional arrays. In c#, a multidimensional array is an array that contains more than one dimension to represent the elements in a tabular format like rows and columns.
In c#, multidimensional arrays can support either two or three-dimensional series. To create multi-dimensional arrays, we need to use a comma (,) separator inside the square brackets.
C# Multi-Dimensional Array Declaration
In c#, Multidimensional Arrays can be declared by specifying the data type of elements followed by the square brackets [] with comma (,) separator. The following are examples of creating two or three-dimensional arrays in the c# programming language.
Question:
Create a complete C# program that will compute the average of all elements in array x
int [,] x = new int[4, 5] { { 4, 5, 6, 2, 12 }, { 10, 25, 33, 22, 11 },{ 211, 32, 43, 54, 65 }, { 3, 2, 1, 5, 6 } };
Average
Solution
- Use for loop get array x elements values
- Add values
- Divide results by no. of values
Code
using System;
namespace Module7
{
public class Module7
{
public static void Main(string[] args)
{
//initilizing array
int[,] x = new int[4, 5]
{
{ 4, 5, 6, 2, 12 },
{ 10, 25, 33, 22, 11 },
{ 211, 32, 43, 54, 65 },
{ 3, 2, 1, 5, 6 }
};
Console.WriteLine("---Two dimensional array elements---");
// use for loop get array x elements
for(int y=0; y<4; y++)
{
int sum = 0;
double avg = 0;
for (int z = 0; z < 5; z++)
{
Console.WriteLine("X[{0},{1}] = {2}", y, z, x[y, z]);
// sum the values in the array
sum += x[y, z];
}
// compute the average of all elements in array x
avg = (double)sum / 5;
Console.WriteLine("Average is " + avg);
}
Console.ReadLine();
}
}
}
Reference :
C# Sharp Exercises: Print the average of four numbers
https://www.w3resource.com/csharp-exercises/basic/csharp-basic-exercise-9.php
C# Multidimensional Arrays
https://www.tutlane.com/tutorial/csharp/csharp-multidimensional-arrays
How to calculate the average of each row in multidimensional array
https://stackoverflow.com/questions/41582366/how-to-calculate-the-average-of-each-row-in-multidimensional-array