Download presentation
Presentation is loading. Please wait.
1
Module8 Multi-dimensional Array
Thanawin Rakthanmanon Create by: Aphirak Jansang Computer Engineering Department Kasetsart University, Bangkok THAILAND
2
Outlines Array Review Multi-dimensional Array
3
Do you remember how to declare Array?
Array for keeping 50 student's names string [ ] NAME = new string[50]; Array for keeping 50 student's IDs string [ ] ID = new string[50]; Array for keeping 50 student’s GPAs double[ ] GPA = new double[50];
4
examples int [] score = new int[6]; 1 2 3 4 5 score int [] score = new int[4] {5,6,7,9}; 1 2 3 score 5 6 7 9
5
Accessing Array Elements
Supply an integer index for accessing array elements indexes are zero-based int [] score = new int[4]; 1 2 3 score -3 4 7 score[0] = -3; score[2+1] = 7; Score[3-1] = score[0]+score[3] Console.WriteLine(score[2]); 4
6
How to find Array’s length?
By property Length 5 int [] matrix = new int[5]; Console.WriteLine(matrix.Length); By method GetLength() 7 int [] matrix = new int[7]; Console.WriteLine(matrix.GetLength(0));
7
How to access Array's member ?
Displaying all members in Array ‘SCORE’ Finding summation of all members in Array ‘SCORE’ for (int i = 0; i< SCORE.Length; i++) { Console.WriteLine(SCORE[i]); } double sum = 0; for (int i = 0; i< SCORE.Length; i++) { sum = sum + SCORE.Length; }
8
Looping or Iteration in C#
while Iteration for foreach do…while
9
foreach foreach is used to access all elements in an array and do some action repeatedly foreach = “for each element in an array” Syntax foreach (var_declaration in array_name) statement // the above statement will be applied to each element in an array
10
foreach example string s = Console.ReadLine(); int count = 0;
for (int i = 0; i < s.Length; i++){ if(s[i] == 'A') count++; } string s = Console.ReadLine(); int count = 0; foreach (char c in s) { if (c == 'A') count++; }
11
Outlines Array Review Multi-dimensional Array
12
Multi-dimensional Array’s declaration
Syntax: <type> [ , ] <name>; <type> [ , , ] <name>; Creation: <name> = new <type>[<dim1>,<dim2>]; 2 dimensions 3 dimensions 2 dimensions
13
Array Declaration Example
int [ , ] grid2; grid2 = new int [3,2]; int [ , , ] grid3; grid3 = new int [3, 2, 4];
14
How to find Array’s #dimension?
By property Rank 1 int [] matrix = new int[5]; Console.WriteLine(matrix.Rank); 2 int [,] matrix = new int[5,2]; Console.WriteLine(matrix.Rank); int [,,] matrix = new int[5,2,3]; Console.WriteLine(matrix.Rank); 3
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.