Multidimensional Arrays: Ali Shakir Alahmed
Multidimensional Arrays: Ali Shakir Alahmed
Multidimensional Arrays: Ali Shakir Alahmed
Multidimensional Arrays
2022–2023
What is Multidimensional Array?
• Multidimensional arrays have more than one
dimension (2, 3, …)
– The most important multidimensional arrays are the
2-dimensional
• Known as matrices
• Example of matrix of integers with 2 rows and 4
columns:
0 1 2 3
0 5 0 -2 4
1 5 6 7 8
Multi Dimensional Arrays Definition
Arrays can have more than one dimension. For example, a two-dimensional
array of four rows and two columns. It might have two, three, etc.
dimensions.
{13,14,15,16},
{20,21,22,23},
{31,32,33,34}
};
Console.WriteLine(A[0, 2]); 15
}}
Two-Dimensional Array: Declaration Example
double[ , ] hillHeight = { { 1, 2, 3, 4 }, { 2, 3, 4, 5 }, { 3, 4, 5, 6 } };
4 Columns
Row 0
3 Rows
Row 1
Row 2
using System;
class Program
{
public static void Main()
{
int[,] A = new int[,]{{10, 20, 30},{ 40, 50, 60} };
using System;
class Pogram
{ Console Window
static void Main() 123456
{ int[,] A={{1, 2, 3},{4, 5, 6}};
Total: 21
int total = 0;
for (int r = 0; r < A.GetLength(0); r++) Average: 3.5
{ for (int c = 0; c < A.GetLength(1); c++)
{ Console.Write(A[r, c]+” “);
total + = A[r, c];
}
}
Console.WriteLine(“\nTotal: {0}”, total);
Console.WriteLine(“Average: {0}”, (total/6.0));
}
}
for(i=0;i<n;i++)
{ sum= sum+arr1[i,i]; }
Console.Write("Addition of the main Diagonal elements is :{0}\
n",sum);
Find sum of Second diagonal of a matrix
public static void Main()
{ int i,j,sum=0,n,m=0;
int[,] arr1 = new int[5,5];
Console.Write("Input elements in the matrix:\n");
for(i=0; i<5;i++)
{ for(j=0;j<5;j++)
{
arr1[i,j]= int.Parse (Console.ReadLine());
}
}
// calculate the sum of second diagonals
for(i=0;i<5;i++)
{ for(j=0;j<5;j++)
{
if (i+j == 4)
{ sum= sum+arr1[i,j]; }
}
}
Console.Write("Addition of the second Diagonal elements is :
{0}\n",sum);
}
}
HOME WORK