Download presentation
Presentation is loading. Please wait.
Published byMitchell Mosley Modified over 8 years ago
1
Lecture 03 Dr. Eng. Ibrahim El-Nahry Arrays
2
2 Learning Objectives Introduction to Arrays Declaring and referencing arrays Initializing Arrays Arrays in Method Arrays of Objects Arrays as Method arguments For-loops, foreach-loop and arrays
3
3 Arrays An array stores multiple elements of the same type that type can be simple (value) types or objects for arrays of simple types, each element contains one value of the declared type for arrays of reference types (e.g., objects), every element of the array is a reference to an object of the data type of the array Refer to particular element in the array by position number the name of the array followed by the position number (subscript) of the element in square brackets ([]) [ ] is considered as an operator
4
4 Defining an Array in C# There are two steps in establishing an array. First: Declare an identifier as an array type: Second: Allocate the actual array object. Example: int[ ] Grades; // Grades will reference an //array of integers : Grades = new int[50]; //Allocate space for //50 integers
5
5 One-Dimensional arrays: Declaration and Instantiation A one-dimensional array stores a list of values An array can be allocated using the keyword new to specify how many elements the array should hold int[ ] Grades = new int[50];
6
6 bool[] flags; // declare flags flags = new bool[20]; // create an array and make flags a ref. // now flags is reference to another array flags = new bool[10]; // declare variable grades; create an array; make grades a // reference of the array int[] grades = new int[12]; float[] prices = new float[500]; string[] codes = new string[26]; Time1[] times; times = new Time1[10];
7
7 In general In C#, given a type, the presence of [ ] following the type, represents an array type whose entries are of the specified type: int[ ] //array of integers char[ ] //array of characters double[ ] //an array of doubles.
8
8 Array: An Array of Simple Values A 12-element array of values. -45 6 0 72 1543 -89 0 62 -3 1 6453 -78 grades[ 11 ] grades[ 10 ] grades[ 9 ] grades[ 8] grades[ 7 ] grades[ 4 ] grades[ 3 ] grades[ 2 ] grades[ 1 ] grades[ 0 ] grades[ 6 ] grades[ 5 ] position number (index or subscript) of the element within array grades grades
9
9 Array: An Array of Objects A 10-element array of objects ref to obj 0 ref to obj 1 ref to obj 2 ref to obj 3 ref to obj 4 ref to obj 5 ref to obj 6 ref to obj 7 ref to obj 8 ref to obj 9times[ 9 ] times[ 8] times[ 7 ] times[ 4 ] times[ 3 ] times[ 2 ] times[ 1 ] times[ 0 ] times[ 6 ] times[ 5 ] position number (index or subscript) of the element within array times times
10
10 Arrays as Objects In C#, an array behaves very much like an object declaration and instantiation are like objects declare an array variable create an array using new make a variable a reference of an array parameter passing is similar to objects an array has the Length property
11
11 Array: Length Each array has a public property called Length that stores the size of the array once an array is created, it has a fixed size It is referenced using the array name (just like any other object): grades.Length Note that Length holds the number of elements, not the largest index grades.Length has value 12. There are twelve items in the array.
12
12 Array Instantiation and Initialization in One Step An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Allocate space for the array – number of elements in initializer list determines the size of array Elements in array are initialized with the values in the initializer list The new operator is not used Examples: int[] units = {147, 323, 89, 933, 540}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}; string[] wordList = { “ cs112 “, “ computer", “ television"};
13
13 int[ ] List = {1,2,10,20,30,11,12}; List[0] has value 1. List[1] has value 2. List[2] has value 10. List[3] has value 20. List[4] has value 30. List[5] has value 11. List[6] has value 12.
14
14 Terminology In the example on the previous page: List is the “name” of the array. Like a variable identifier it can be any legal user-defined identifier. List[i] Placing [ ] after the name “dereferences” the array and gives the individual element. The quantity inside the [ ] is called the index. It must be an integer valued expression whose value is from 0 to N-1 where N is the number of elements in the array.
15
15 Array and Bound An index used in an array reference must specify a valid element That is, the index value must be in bounds (0 to N-1), where N is the length For example, if the array grades can hold 12 values, it can only be indexed using the numbers 0 to 11 for (int index=0; index <= grades.Length; index++) scores[index] = index*50 + epsilon; problem It’s common to introduce off-by-one errors when using arrays
16
16 1 // InitArray 2 // Different ways of initializing arrays. 3 4 using System; 5 using System.Windows.Forms; 6 7 class InitArray 8 { 9 // main entry point for application 10 static void Main( string[] args ) 11 { 12 string output = ""; 13 14 int[] x; // declare reference to an array 15 x = new int[ 10 ]; // dynamically allocate array and set 16 // default values 17 18 // initializer list specifies number of elements 19 // and value of each element 20 int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 21 22 const int ARRAY_SIZE = 10; // named constant 23 int[] z; // reference to int array 24 25 // allocate array of ARRAY_SIZE (i.e., 10) elements 26 z = new int[ ARRAY_SIZE ]; 27 28 // set the values in the array 29 for ( int i = 0; i < z.Length; i++ ) 30 z[ i ] = 2 + 2 * i; 31 32 output += "Subscript\tArray x\tArray y\tArray z\n"; 33 Declare an integer array variable x Create an array of size 10; x is a ref. to it Declare an integer array and initialize it with values Declare a constant ARRAY_SIZE Declare z Create an array of size ARRAY_SIZE; z is a reference to it. Initialize the elements in z using a for loop
17
17 InitArray Program Output 34 // output values for each array 35 for ( int i = 0; i < ARRAY_SIZE; i++ ) 36 output += i + "\t" + x[ i ] + "\t" + y[ i ] + 37 "\t" + z[ i ] + "\n"; 38 39 MessageBox.Show( output, 40 "Initializing an array of int values", 41 MessageBoxButtons.OK, 42 MessageBoxIcon.Information ); 42 43 } // end Main 44 45 } // end class InitArray Add values in the arrays to output
18
18 Parameter passing: Two Types of Variables A variable represents a cell in memory Value type int, char, byte, float, double, string A value type variable stores a value of the type of the variable in the memory int x = 45; double y = 45.12; Reference type A variable that “stores” object or array actually stores a reference to an object or array, e.g., A reference is a location in computer’s memory where the object or array itself is stored Time3 t1; t1 = new Time3(11, 45, 59); 45 x 45.12 y t1 11 45 59
19
19 Implications of the Two Types of Variables: Assignment An assignment of one value variable to another value variable copies the value, e.g., int x = 45; double y = 45.12; int z; z = x; An assignment of one reference variable to another reference variable copies the reference, e.g., Time3 t1; t1 = new Time3(11, 45, 59); Time3 t2; t2 = t1; t1 45 x 45.12 y z 45 t2 11 45 59
20
20 Implications of the Two Types of Variables: Change Change the value of one value variable will not change the other: int x = 45; double y = 45.12; int z; z = x; x = 23; Change the content (state) by one reference may affect another reference variable Time3 t1; t1 = new Time3(11, 45, 59); Time3 t2; t2 = t1; t2.SetTime(22, 22, 22); t1 45 x 45.12 y z 45 t2 23 11 45 59 22
21
21 Passing Arguments by Value and by Reference Passing a value type argument to methods The value of an actual argument is copied to the formal argument The formal argument has its own memory location Any changes to the formal argument in the method do not affect the actual argument Passing a reference type argument to methods A copy of the reference to the object/array is made to the formal argument Any changes to the contents of the object/array in the method, do affect the object/array outside the method Because both the formal argument and the actual argument are reference to the same object/array
22
22 Calling a Method: Reference Each time a method is called, the actual arguments in the invocation are copied into the formal arguments If a value type, it is the value If a reference type, it is the reference static void DoubleArray (int[] array) { for (int i = 0; i < array.Length; i++) array[i] *= 2; } DoubleArray (array); int[] array = {1, 2, 3}; array 1 2 3 2 4 6
23
23 Calling a Method: Side Effect of Reference If an argument is a reference type, then modifying the content/state of the array/object through the reference will have side effect static void DoubleArray (int[] array) { for (int i = 0; i < array.Length; i++) array[i] *= 2; } DoubleArray (array); int[] array = {1, 2, 3}; array 1 2 3 2 4 6 i
24
24 Calling a Method: Side Effect static void DoubleArray (int[] array) DoubleArray( array ); int[] array = {1, 2, 3}; array 1 2 3 2 4 6 { for (int i = 0; i < array.Length; i++) array[i] *= 2; } i Each time a method is called, the actual arguments in the invocation are copied into the formal arguments If a value type, then it is the value that is copied If a reference type, then it is the reference that is copied The formal argument and the actual argument are different variables, with different memory locations. 2 4 6 8 array = new int[] {2, 4, 6, 8};
25
Sorting Arrays Sorting data is important in many applications Bubble Sort – array of size n Make n passes through the array For each pass, compare every pair of successful elements If the first is larger then the second, swap the elements Easy to program Runs slowly.NET Framework includes high-speed sorting capabilities
26
2002 Prentice Hall. All rights reserved. Outline 1 // Fig. 7.10: BubbleSorter.cs 2 // Sorting an array's values into ascending order. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class BubbleSorter : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button sortButton; 13 private System.Windows.Forms.Label outputLabel; 14 15 // Visual Studio.NET generated code 16 17 [STAThread] 18 static void Main() 19 { 20 Application.Run( new BubbleSorter() ); 21 } 22 23 private void sortButton_Click( object sender, 24 System.EventArgs e ) 25 { 26 int[] a = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; 27 28 outputLabel.Text += "Data items in original order\n"; 29 30 for ( int i = 0; i < a.Length; i++ ) 31 outputLabel.Text += " " + a[ i ]; 32 33 // sort elements in array a 34 BubbleSort( a ); 35 Declare and initialize array aOutput the contents of array aCall method Bubble sort on array a
27
2002 Prentice Hall. All rights reserved. Outline 36 outputLabel.Text += "\n\nData items in ascending order\n"; 37 38 for ( int i = 0; i < a.Length; i++ ) 39 outputLabel.Text += " " + a[ i ]; 40 41 } // end method sortButton_Click 42 43 // sort the elements of an array with bubble sort 44 public void BubbleSort( int[] b ) 45 { 46 for ( int pass = 1; pass < b.Length; pass++ ) // passes 47 48 for ( int i = 0; i < b.Length - 1; i++ ) // one pass 49 50 if ( b[ i ] > b[ i + 1 ] ) // one comparison 51 Swap( b, i ); // one swap 52 } 53 54 // swap two elements of an array 55 public void Swap( int[] c, int first ) 56 { 57 int hold; // temporary holding area for swap 58 59 hold = c[ first ]; 60 c[ first ] = c[ first + 1 ]; 61 c[ first + 1 ] = hold; 62 } 63 } Output sorted array a Perform b.Length-1 passes Perform contents of for loop for each element of array b If an given element is bigger then the following element, swap the elements Swaps two elements of an array
28
28 Two-Dimensional Arrays A two-dimensional array, also called double-subscripted array, can be thought of as a table of values, with rows and columns a two-dimensional array element is referenced using two index numbers
29
29 Two Types of Double-Subscripted Arrays rectangular arrays often represent tables in which each row is the same size and each column is the same size, e.g., int[,] a1 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; int[,] a11 = new int[3,4]; jagged arrays arrays of arrays arrays that compose jagged arrays can be of different lengths, e.g., int[][] array2 = new int[ 3 ][]; array2[ 0 ] = new int[] { 1, 2 }; array2[ 1 ] = new int[] { 3 }; array2[ 2 ] = new int[] { 4, 5, 6 }; array2[2][1] = 3;
30
30 Double-Subscripted Arrays Double-subscripted array with three rows and four columns. Row 0 Row 1 Row 2 Column 1Column 0Column 2Column 3 a[0][0]a[0][3]a[0][1]a[0][2] a[1][0]a[1][3]a[1][1]a[1][2] a[2][0]a[2][3] a[2][2] Column index (or subscript) Row index (or subscript) Array name a[2][1]
31
31 1 // TwoDimensionalArrays 2 // Initializing two-dimensional arrays. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class TwoDimensionalArrays : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button showOutputButton; 13 private System.Windows.Forms.Label outputLabel; 14 15 // Visual Studio.NET generated code 16 17 [STAThread] 18 static void Main() 19 { 20 Application.Run( new TwoDimensionalArrays() ); 21 } 22 23 private void showOutputButton_Click( object sender, 24 System.EventArgs e ) 25 { 26 // declaration and initialization of rectangular array 27 int[,] array1 = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; 28 29 // declaration and initialization of jagged array 30 int[][] array2 = new int[ 3 ][]; 31 array2[ 0 ] = new int[] { 1, 2 }; 32 array2[ 1 ] = new int[] { 3 }; 33 array2[ 2 ] = new int[] { 4, 5, 6 }; 34 35 outputLabel.Text += "Values in array1 by row are\n"; Declare and initialize a rectangular integer array named array1 Declare a jagged array named array2 with 3 rows Initialize the first element in array2 to be an array that contains two integers Initialize the second element in array2 to be an array that contains 1 integer Initialize the third element in array2 to be an array that contains 3 integers
32
32 TwoDimensionalArrays Program Output 36 37 // output values in array1 38 for ( int i = 0; i < array1.Length; i++ ) 39 { 40 for ( int j = 0; j < array1[i].Length; j++ ) 41 outputLabel.Text += array1[ i, j ] + " "; 42 43 outputLabel.Text += "\n"; 44 } 45 46 outputLabel.Text += "\nValues in array2 by row are\n"; 47 48 // output values in array2 49 for ( int i = 0; i < array2.Length; i++ ) 50 { 51 for ( int j = 0; j < array2[ i ].Length; j++ ) 52 outputLabel.Text += array2[ i ][ j ] + " "; 53 54 outputLabel.Text += "\n"; 55 } 56 57 } // end method showOutputButton_Click 58 59 } // end class TwoDimensionalArrays
33
33 DoubleArray 1 // : DoubleArray 2 // Manipulating a double-subscripted array. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class DoubleArray : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button showOutputButton; 13 private System.Windows.Forms.Label outputLabel; 14 15 private int[][] grades; 16 private int students, exams; 17 18 // Visual Studio.NET generated code 19 20 [STAThread] 21 static void Main() 22 { 23 Application.Run( new DoubleArray() ); 24 } 25 26 private void showOutputButton_Click( object sender, 27 System.EventArgs e ) 28 29 { 30 grades = new int[ 3 ][]; 31 grades[ 0 ] = new int[]{ 77, 68, 86, 73 }; 32 grades[ 1 ] = new int[]{ 96, 87, 89, 81 }; 33 grades[ 2 ] = new int[]{ 70, 90, 86, 81 }; 34 Initialize array grades to have 3 rows Initialize each element in array grades
34
34 35 students = grades.Length; // number of students 36 exams = grades[ 0 ].Length; // number of exams 37 38 // line up column headings 39 outputLabel.Text += " "; 40 41 // output the column headings 42 for ( int i = 0; i < exams; i++ ) 43 outputLabel.Text += "[" + i + "] "; 44 45 // output the rows 46 for ( int i = 0; i < students; i++ ) 47 { 48 outputLabel.Text += "\ngrades[" + i + "] "; 49 50 for ( int j = 0; j < exams; j++ ) 51 outputLabel.Text += grades[ i ][ j ] + " "; 52 } 53 54 outputLabel.Text += "\n\nLowest grade: " + Minimum() + 55 "\nHighest grade: " + Maximum() + "\n"; 56 57 for ( int i = 0; i < students; i++ ) 58 outputLabel.Text += "\nAverage for student " + i + " is " + 59 Average( grades[ i ] ); 60 61 } // end method showOutputButton_Click 62 Output each rowOutput each element of the row Output the minimum and maximum grades Output the average for each row
35
35 63 // find minimum grade in grades array 64 public int Minimum() 65 { 66 int lowGrade = 100; 67 68 for ( int i = 0; i < students; i++ ) 69 70 for ( int j = 0; j < exams; j++ ) 71 72 if ( grades[ i ][ j ] < lowGrade ) 73 lowGrade = grades[ i ][ j ]; 74 75 return lowGrade; 76 } 77 78 // find maximum grade in grades array 79 public int Maximum() 80 { 81 int highGrade = 0; 82 83 for ( int i = 0; i < students; i++ ) 84 85 for ( int j = 0; j < exams; j++ ) 86 87 if ( grades[ i ][ j ] > highGrade ) 88 highGrade = grades[ i ][ j ]; 89 90 return highGrade; 91 } 92 Examine each element in grades array If the current array element is less then the lowest grade, set the value of lowGrade to be the current element Examine each element in grades array If the current array element higher than the highest grade, set the value of highGrade to be the current element
36
36 DoubleArray Program Output 93 // determine average grade for a particular student 94 public double Average( int[] setOfGrades ) 95 { 96 int total = 0; 97 98 for ( int i = 0; i < setOfGrades.Length; i++ ) 99 total += setOfGrades[ i ]; 100 101 return ( double ) total / setOfGrades.Length; 102 } 103 104 } // end class DoubleArray Total the grades for the array Divide the total by the number of grades
37
37 foreach Loop There is a another type of loop that is very simple and useful to iterate through arrays and collections. The basic structure of a foreach loop is: “foreach Statement” For iterating over collections and arrays int[] a = {3, 17, 4, 8, 2, 29}; foreach(int x in a) sum += x; string s = "Hello"; foreach(char ch in s) Console.WriteLine(ch);
38
38 using System; public class SamplesArray { public static void Main() { // Create and initialize a new string array. String[] myArr = {"The", "quick", "brown", "fox", "jumps", "over","the", "lazy", "dog"}; // Display the values of the array. Console.WriteLine("The string array initially contains the following values:"); PrintIndexAndValues(myArr); // Resize the array to a bigger size (five elements larger). Array.Resize(ref myArr, myArr.Length + 5); // Display the values of the array. Console.WriteLine("After resizing to a larger size, "); Console.WriteLine("the string array contains the following values:");
39
39 PrintIndexAndValues(myArr); // Resize the array to a smaller size (four elements). Array.Resize(ref myArr, 4); // Display the values of the array. Console.WriteLine("After resizing to a smaller size, "); Console.WriteLine("the string array contains the following values:"); PrintIndexAndValues(myArr); } public static void PrintIndexAndValues(string[] myArr) { for(int i = 0; i < myArr.Length; i++) { Console.WriteLine(" [{0}] : {1}", i, myArr[i]); } Console.WriteLine(); }
40
40
41
41 Matrix Addition and Subtraction A new matrix C may be defined as the additive combination of matrices A and B where: C = A + B is defined by: Note: all three matrices are of the same dimension
42
42 Addition If and then
43
43 Matrix Addition Example
44
44 Matrix Subtraction C = A - B Is defined by
45
45 Matrix Multiplication Matrices A and B have these dimensions: [r x c] and [s x d]
46
46 Matrix Multiplication Matrices A and B can be multiplied if: [r x c] and [s x d] c = s
47
47 Matrix Multiplication The resulting matrix will have the dimensions: [r x c] and [s x d] r x d
48
48 Computation: A x B = C [2 x 2] [2 x 3]
49
49 Computation: A x B = C [3 x 2][2 x 3] A and B can be multiplied [3 x 3]
50
50 Computation: A x B = C [3 x 2][2 x 3] [3 x 3] Result is 3 x 3
51
using System; namespace Array_Pgm { class MatrixCalc { static int i, j; static void addMatrix(int[,] A, int[,] B, int m, int n) { int[,] C = new int[10, 10]; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) C[i, j] = A[i, j] + B[i, j]; } display(C, m, n); }
52
static void subMatrix(int[,] A, int[,] B, int m, int n) { int[,] C = new int[10, 10]; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) C[i, j] = A[i, j] - B[i, j]; } display(C, m, n); } static void display(int[,] A, int m, int n) { for (i = 0; i < m; i++) { for (j = 0; j < n; j++) Console.Write(A[i, j] + "\t"); Console.WriteLine(); } }
53
static void mulMatrix(int[,]A,int [,]B,int m,int n) { int [,]C = new int[10,10]; for(i=0;i< m;i++) { for(j=0;j< n;j++) { C[i,j] = 0; for(int k=0;k< n;k++) { C[i,j] = C[i,j] + A[i,k] * B[k,j]; } } } display(C, m, n); }
54
public static void Main(string[] args) { // Input First Matrix say A; int m, n; Console.Write("Enter No Of Roes And Columns Of Matrix A : "); m =Convert.ToInt32(Console.ReadLine()); n =Convert.ToInt32(Console.ReadLine()); int[,] A = new int[10, 10]; Console.Write("\nEnter The First MNatrix : "); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) A[i, j] =Convert.ToInt32(Console.ReadLine()); } // Input Second Matrix say B; int p, q; Console.Write("Enter No Of Rows And Columns Of Matrix B :"); p =Convert.ToInt32(Console.ReadLine()); q =Convert.ToInt32(Console.ReadLine()); int[,] B = new int[10, 10]; Console.Write("\nEnter The Second Matrix:"); for (i = 0; i < p; i++) { for (j = 0; j < q; j++) B[i, j] = Convert.ToInt32(Console.ReadLine()); } Console.Clear();
55
// Display The Two Matrixes Console.WriteLine("\nMatrix A : "); display(A, m, n); Console.WriteLine("\nMatrix B: "); display(B, p, q); // Menu Console.WriteLine("**** MENU For Matrix Opearations *****"); Console.WriteLine(" 1. Addition"); Console.WriteLine(" 2. Subtraction"); Console.WriteLine(" 3. Multiplication"); Console.WriteLine(" 4. Exit"); Console.WriteLine("Enter Your option"); int choice = Convert.ToInt32(Console.ReadLine());
56
switch (choice) { case 1: if (m == p && n == q) { Console.WriteLine("Addition "); addMatrix(A, B, m, n); } else Console.WriteLine("ERROR !!!!!! Rows and Columns Of Both martixes should be same"); break; case 2: if (m == p && n == q) { Console.WriteLine("Subtraction "); subMatrix(A, B, m, n); } else Console.WriteLine("ERROR !!!!!! Rows and Columns Of Both martixes should be same"); break; case 3: if (n == p) { Console.WriteLine("Multiplication: "); mulMatrix(A, B, m, q); } else Console.WriteLine("ERROR !!!!!! Column of First matrix and Row Of Second Matrix should be same"); break; case 4: Console.Beep(1000, 1000); break; /* default: Console.WriteLine("Error");*/ } } } }
57
57 Summary Array is collection of "same type" data Indexed variables of array used just like any other simple variables for-loop "natural" way to traverse arrays foreach-loop is a another type of loop that is very simple and useful to iterate through arrays Programmer responsible for staying "in bounds" of array Array parameter is "new" kind Similar to call-by-reference
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.