Lecture 03 Dr. Eng. Ibrahim El-Nahry Arrays. 2 Learning Objectives Introduction to Arrays Declaring and referencing arrays Initializing Arrays Arrays.

Slides:



Advertisements
Similar presentations
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Advertisements

Arrays. Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays 6.3Declaring Arrays 6.4Examples Using Arrays 6.5Passing.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Chapter 9: Arrays and Strings
 2003 Prentice Hall, Inc. All rights reserved Multiple-Subscripted Arrays Multiple subscripts –a[ i ][ j ] –Tables with rows and columns –Specify.
Chapter 9: Arrays and Strings
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
 2002 Prentice Hall. All rights reserved. 1 Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Allocating Arrays 7.4 Examples Using.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections.
Advanced Programming Array.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 - Arrays Outline 6.1Introduction 6.2Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 8 Arrays and Strings
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
Chapter 6 Arrays Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Algorithm and Programming Array Dr. Ir. Riri Fitri Sari MM MSc International Class Electrical Engineering Dept University of Indonesia 15 March 2009.
 Pearson Education, Inc. All rights reserved Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 Pearson Education, Inc. All rights reserved Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Group of consecutive memory locations –Same name and type To refer to an element, specify.
C Lecture Notes 1 Arrays Lecture 6. C Lecture Notes 2 6.1Introduction Arrays –Structures of related data items –Static entity – same size throughout program.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Vectors.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
C++ Programming Lecture 16 Arrays – Part III The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Arrays 3.Declaring Arrays 4.Examples Using Arrays 5.Multidimensional Arrays 6.Multidimensional.
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
A DVANCED P ROGRAMMING C HAPTER 8: A RRAYS Dr Shahriar Bijani Spring 2016.
Lecture 4: Chapter 7 - Arrays Outline Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods.
7.1 Introduction Arrays Arrays are data structures consisting of data items of the same type “Static” entities They remain the same size once they are.
Advanced Programming Chapter 8: Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Arrays Outline Introduction Arrays Declaring Arrays
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Visual Programming COMP-315
Chapter 3 Arrays Dr. A. PHILIP AROKIADOSS Assistant Professor
Arrays.
Presentation transcript:

Lecture 03 Dr. Eng. Ibrahim El-Nahry Arrays

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 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 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 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 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 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 Array: An Array of Simple Values A 12-element array of values 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 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 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 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 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 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 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 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 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 = ""; int[] x; // declare reference to an array 15 x = new int[ 10 ]; // dynamically allocate array and set 16 // default values // 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 }; const int ARRAY_SIZE = 10; // named constant 23 int[] z; // reference to int array // allocate array of ARRAY_SIZE (i.e., 10) elements 26 z = new int[ ARRAY_SIZE ]; // set the values in the array 29 for ( int i = 0; i < z.Length; i++ ) 30 z[ i ] = * i; 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 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"; MessageBox.Show( output, 40 "Initializing an array of int values", 41 MessageBoxButtons.OK, 42 MessageBoxIcon.Information ); } // end Main } // end class InitArray Add values in the arrays to output

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 y t

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 y z 45 t

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 y z 45 t

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 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

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 i

24 Calling a Method: Side Effect static void DoubleArray (int[] array) DoubleArray( array ); int[] array = {1, 2, 3}; array { 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 array = new int[] {2, 4, 6, 8};

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

 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; // Visual Studio.NET generated code [STAThread] 18 static void Main() 19 { 20 Application.Run( new BubbleSorter() ); 21 } private void sortButton_Click( object sender, 24 System.EventArgs e ) 25 { 26 int[] a = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; outputLabel.Text += "Data items in original order\n"; for ( int i = 0; i < a.Length; i++ ) 31 outputLabel.Text += " " + a[ i ]; // 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

 2002 Prentice Hall. All rights reserved. Outline 36 outputLabel.Text += "\n\nData items in ascending order\n"; for ( int i = 0; i < a.Length; i++ ) 39 outputLabel.Text += " " + a[ i ]; } // end method sortButton_Click // 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 for ( int i = 0; i < b.Length - 1; i++ ) // one pass if ( b[ i ] > b[ i + 1 ] ) // one comparison 51 Swap( b, i ); // one swap 52 } // swap two elements of an array 55 public void Swap( int[] c, int first ) 56 { 57 int hold; // temporary holding area for swap 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 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 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 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 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; // Visual Studio.NET generated code [STAThread] 18 static void Main() 19 { 20 Application.Run( new TwoDimensionalArrays() ); 21 } 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 } }; // 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 }; 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 TwoDimensionalArrays Program Output // 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 ] + " "; outputLabel.Text += "\n"; 44 } outputLabel.Text += "\nValues in array2 by row are\n"; // 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 ] + " "; outputLabel.Text += "\n"; 55 } } // end method showOutputButton_Click } // end class TwoDimensionalArrays

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; private int[][] grades; 16 private int students, exams; // Visual Studio.NET generated code [STAThread] 21 static void Main() 22 { 23 Application.Run( new DoubleArray() ); 24 } private void showOutputButton_Click( object sender, 27 System.EventArgs e ) { 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 35 students = grades.Length; // number of students 36 exams = grades[ 0 ].Length; // number of exams // line up column headings 39 outputLabel.Text += " "; // output the column headings 42 for ( int i = 0; i < exams; i++ ) 43 outputLabel.Text += "[" + i + "] "; // output the rows 46 for ( int i = 0; i < students; i++ ) 47 { 48 outputLabel.Text += "\ngrades[" + i + "] "; for ( int j = 0; j < exams; j++ ) 51 outputLabel.Text += grades[ i ][ j ] + " "; 52 } outputLabel.Text += "\n\nLowest grade: " + Minimum() + 55 "\nHighest grade: " + Maximum() + "\n"; for ( int i = 0; i < students; i++ ) 58 outputLabel.Text += "\nAverage for student " + i + " is " + 59 Average( grades[ i ] ); } // 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 63 // find minimum grade in grades array 64 public int Minimum() 65 { 66 int lowGrade = 100; for ( int i = 0; i < students; i++ ) for ( int j = 0; j < exams; j++ ) if ( grades[ i ][ j ] < lowGrade ) 73 lowGrade = grades[ i ][ j ]; return lowGrade; 76 } // find maximum grade in grades array 79 public int Maximum() 80 { 81 int highGrade = 0; for ( int i = 0; i < students; i++ ) for ( int j = 0; j < exams; j++ ) if ( grades[ i ][ j ] > highGrade ) 88 highGrade = grades[ i ][ j ]; 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 DoubleArray Program Output 93 // determine average grade for a particular student 94 public double Average( int[] setOfGrades ) 95 { 96 int total = 0; for ( int i = 0; i < setOfGrades.Length; i++ ) 99 total += setOfGrades[ i ]; return ( double ) total / setOfGrades.Length; 102 } } // end class DoubleArray Total the grades for the array Divide the total by the number of grades

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 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 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

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 Addition If and then

43 Matrix Addition Example

44 Matrix Subtraction C = A - B Is defined by

45 Matrix Multiplication Matrices A and B have these dimensions: [r x c] and [s x d]

46 Matrix Multiplication Matrices A and B can be multiplied if: [r x c] and [s x d] c = s

47 Matrix Multiplication The resulting matrix will have the dimensions: [r x c] and [s x d] r x d

48 Computation: A x B = C [2 x 2] [2 x 3]

49 Computation: A x B = C [3 x 2][2 x 3] A and B can be multiplied [3 x 3]

50 Computation: A x B = C [3 x 2][2 x 3] [3 x 3] Result is 3 x 3

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); }

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(); } }

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); }

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();

// 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());

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 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