Arrays. Arrays: Declaration and Instantiation. Array: An Array of Simple Values

Similar documents
An array can hold values of any type. The entire collection shares a single name

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

C# and.net (1) cont d

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

C++ PROGRAMMING SKILLS Part 4: Arrays

C Arrays Pearson Education, Inc. All rights reserved.

Tutorial 5 Completing the Inventory Application Introducing Programming

Tutorial 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and Arithmetic

Arrays (Deitel chapter 7)

Flag Quiz Application

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Chapter 6: Using Arrays

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

CSC 330 Object-Oriented Programming. Encapsulation

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

Arrays. Week 4. Assylbek Jumagaliyev

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals

Object Oriented Programming. Java-Lecture 6 - Arrays

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Chapter 7: Arrays and the ArrayList Class

Polymorphism. Polymorphism. CSC 330 Object Oriented Programming. What is Polymorphism? Why polymorphism? Class-Object to Base-Class.

Data Types. Operators, Assignment, Output and Return Statements

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

C/C++ Programming Lecture 18 Name:

Multiple-Subscripted Arrays

CS 106 Introduction to Computer Science I

Class C{ int a; } what variables below are objects : a. C c; b. String str; c. Scanner scanner; d. int num; e. float f;

Computer Science & Engineering 150A Problem Solving Using Computers

TOPICS TO COVER:-- Array declaration and use.

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Introduction to Computer Science Midterm 3 Fall, Points

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Example: Computing prime numbers

Arrays and Collections. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

Classes in C# namespace classtest { public class myclass { public myclass() { } } }

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

Introduction to Programming Using Java (98-388)

Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 25, 2016

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Chapter 10 - Notes Applications of Arrays

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

CS313D: ADVANCED PROGRAMMING LANGUAGE

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

Array. Arrays. Declaring Arrays. Using Arrays

Computer Programming Lecture 14 Arrays (Part 2)

PLD Semester Exam Study Guide Dec. 2018

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Student Performance Q&A:

Chapter 6: Arrays. Starting Out with Games and Graphics in C++ Second Edition. by Tony Gaddis

Last Class. More on loops break continue A bit on arrays

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

CS162: Introduction to Computer Science II

Last Class. While loops Infinite loops Loop counters Iterations

Objectives of This Chapter

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays and ArrayLists. David Greenstein Monta Vista High School

Instructor: Eng.Omar Al-Nahal

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays

Chapter 7 Array. Array. C++, How to Program

COMP 202. Programming With Arrays

Lexical Considerations

1 Lexical Considerations

Search,Sort,Recursion

Lexical Considerations

Chapter 9 Introduction to Arrays. Fundamentals of Java

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

by Pearson Education, Inc. All Rights Reserved. 2

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7

Introduction to Microsoft.NET

Pace University. Fundamental Concepts of CS121 1

CS 112 Introduction to Programming

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Lecture 04 FUNCTIONS AND ARRAYS

ECE 122. Engineering Problem Solving with Java

Array. Prepared By - Rifat Shahriyar

Transcription:

What Are Arrays? CSC 0 Object Oriented Programming Arrays An array is a collection variable Holds multiple values instead of a single value An array can hold values of any type Both objects (reference) and primitive values Each object or value must be of the same type The entire collection shares a single name Individual objects (values) are called elements Elements are accessed by means of their position You'll use a subscript or index to specify position Array Variables In C#, (unlike C++/Pascal) array variables are references A little like object variables Array variables refer to a collection of values 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 Arrays: Declaration and Instantiation Array: An Array of Simple Values An array can be allocated using the keyword new to specify how many elements the array should hold 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]; grades grades[ 0 ] grades[ 1 ] grades[ 2 ] grades[ ] grades[ 4 ] -45 6 0 72 154 // 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]; position number (index or subscript) of the element within array grades grades[ 5 ] grades[ 6 ] grades[ 7 ] grades[ 8] grades[ 9 ] grades[ 10 ] -89 0 62-1 645 Time1[] times; times = new Time1[10]; grades[ 11 ] -78 5 A 12-element array of values. 6 1

Array: An Array of Objects Summary of Operators times position number (index or subscript) of the element within array times times[ 0 ] times[ 1 ] times[ 2 ] times[ ] times[ 4 ] times[ 5 ] times[ 6 ] times[ 7 ] times[ 8] times[ 9 ] ref to obj 0 ref to obj 1 ref to obj 2 ref to obj ref to obj 4 ref to obj 5 ref to obj 6 ref to obj 7 ref to obj 8 ref to obj 9 Operators Associativity Type () []. ++ -- left to right highest (unary postfix) ++ -- + -! (type) right to left unary (unary prefix) * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR left to right boolean logical inclusive OR && left to right logical AND left to right logical OR?: right to left conditional = += -= *= /= %= right to left assignment Precedence and associativity of the operators discussed so far. A 10-element array of objects 7 8 Arrays as Objects Array: Length 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 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 9 10 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 yg grades can hold 12 values, it can only be indexed using the numbers 0 to 11 problem for (int index=0; index <= grades.length; index++) scores[index] = index*50 + epsilon; It s common to introduce off-by-one errors when using arrays Array Instantiation and Initialization in One Step: Initializer List 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, 2, 89, 9, 540; char[] lettergrades = 'A', 'B', 'C', 'D', 'F'; string[] wordlist = cs112, computer", television"; 11 12 2

1 // InitArray.cs Declare an integer 2 // Different ways of initializing arrays. 4 array variable x using System; InitArray.cs 5 using System.Windows.Forms; Create an array of 6 7 class InitArray size 10; x is a ref. 8 to it 9 // main entry point for application 10 static void Main( string[] args ) Declare an integer 11 array and initialize it 12 string output = ""; 1 with values 14 int[] x; // declare reference an array to 15 x = new int[ // dynamically allocate array and 10 ]; set 16 // default values Declare a constant 17 ARRAY_SIZE 18 // initializer iti list specifies number of elements 19 // and value each element of 20 int[] y = 2, 27, 64, 18, 95, 14, 90, 70, 60, 7 ; Declare z 21 22 const int ARRAY_SIZE = 10; // named constant 2 int[] z; // reference to int array 25 Create an array of size // allocate array of ARRAY_SIZE (i.e., 10) elements ARRAY_SIZE; z is a 26 z = new int[ ARRAY_SIZE ]; 27 reference to it. 28 // set the values in the array 29 for ( int i = 0; i < z.length; i++ ) Initialize the elements in z 0 1 z[ i ] = 2 + 2 * i; using a for loop 2 output += "Subscript\tArray x\tarray y\tarray z\n"; 4 // output values for each array 5 for ( int i = 0; i < ARRAY_SIZE; i++ ) 6 output += i + "\t" + x[ i ] + "\t" + y[ i ] + 7 "\t" + z[ i ] + "\n"; 8 9 MessageBox.Show( output, 40 "Initializing an array of int values", 41 MessageBoxButtons.OK, 42 MessageBoxIcon.Information ); 42 4 // end Main 44 45 // end class InitArray InitArray.cs Add values in the arrays to output 1 // SumArray.cs 2 // Computing the sum of the elements in an array. 4 using System; Declare integer array a 5 6 using System.Windows.Forms; and initialize it 7 class SumArray 8 9 // main entry point for application Total the contents of 10 11 static void Main( string[] args ) array a 12 int[] a = 1, 2,, 4, 5, 6, 7, 8, 9, 10 ; 1 int total = 0; 14 15 for ( int i = 0; i < a.length; i++ ) 16 total += a[ i ]; 17 18 MessageBox.Show( "Total of array elements: " + total, t 19 "Sum the an array", elements of 20 MessageBoxButtons.OK, 21 MessageBoxIcon.Information ); 22 2 // end Main 25 // end class SumArray SumArray.cs Recall: 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 Time t1; t1 = new Time(11, 45, 59); x y 45 45.12 t1 11 45 59 16 Implications of the Two Types of Variables: Assignment Implications of the Two Types of Variables: Change 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., Time t1; t1 = new Time(11, 45, 59); Time t2; t2 = t1; t1 t2 x 45 y 45.12 z 45 11 45 59 Change the value of one value variable x will not change the other: int x = 45; y double y = 45.12; int z; z = x; x = 2; Change the content (state) by one reference may affect another reference variable Time t1; t1 = new Time(11, 45, 59); t1 Time t2; t2 = t1; t2.settime(22, 22, 22); t2 45 2 45.12 z 45 22 11 45 22 59 22 17 18

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 Calling a Method 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 that is copied If a reference type, it is the reference that is copied 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 int num = SquareSum (2, ); static int SquareSum (int num1, int num2) num1 = num1 + num2; num1 return num1 * num1; num2 25 19 20 Calling a Method: Value Type Calling a Method: Value Type Even if formal arguments and actual arguments have the same name, modifications to formal arguments in a method will not affect actual arguments int n1 = 2; n1 2 int num1 = 2; num1 2 int n2 = ; n2 int num2 = ; num2 int num = SquareSum (n1, n2); int num = SquareSum (num1, num2); static int SquareSum (int num1, int num2) num1 = num1 + num2; num1 return num1 * num1; num2 25 static int SquareSum (int num1, num1 = num1 + num2; return num1 * num1; int num2) num1 25 num2 21 22 Calling a Method: Using ref/out Passing Arrays to Methods If an argument of a method is ref (or out), then the formal argument and the actual argument are aliases of each other, i.e. they share the same memory cell n1 int n1 = 2; n2 int n2 = ; num int num = SquareSum (ref n1, ref n2); static int SquareSum (ref int num1, ref int num2) num1 = num1 + num2; return num1 * num1; 25 25 What happens when you pass an array variable to a method? [Assume a variable named nums is original array] 2 4

Modifying an Array When passed, the reference to the array is sent Formal argument (ar) and actual argument (nums) both refer to the same array elements This means elements may be modified inside methods void doubleit(double ar[ ]) for (int i = 0; i < ar.length; i++) ar[i] *= 2; Array Copies I Sometimes this behavior causes problems Then, you need to make a copy of your array How do you make a copy of an array? Method 1: The wrong way int [ ] copy = ar; This creates a shallow copy Only the reference is copied 26 Array Copies II Method 2: Use a loop and copy each element int size = ar.length; int [ ] copy = new int[size]; for (int i = 0; i < size; i++) copy[ i ] = ar[ i ]; Problem is, that this is fairly slow and tedious Array Copies III Use the System.Array.Copy() method (page 1185) Two versions (three or five arguments): int len = ar.length; int [] copy = new int[len]; int [] half = new int[len - len/2]; Array.Copy( ar, copy, ar.length); Array.Copy( ar, // Copy from this array len/2, // Starting at this position half, // Copy to this array 0, // Starting at this element half.length); // Copy this many elements 27 28 Returning an Array In C#, methods can also return arrays The return type of the method is type[ ] Inside the method, create a local array variable Process the local variable, and then return it public int[ ] makerandom(int howmany) Random rand = new Random(); int[ ] ar = new int[ howmany ]; for(int i = 0; i < ar.length; i++) return ar; ar[ i ] = rand.next(); 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 int[] array = 1, 2, ; DoubleArray (array); array static void DoubleArray (int[] array) array for (int i = 0; i < array.length; i++) array[i] *= 2; 12 6 0 5

Calling a Method: Side Effect of Reference Calling a Method: Side Effect If an argument is a reference type, then modifying the content/state of the array/object through the reference will have side effect 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. int[] array = 1, 2, ; DoubleArray (array); array static void DoubleArray (int[] array) array for (int i = 0; i < array.length; i++) i array[i] *= 2; 12 6 int[] array = 1, 2, ; DoubleArray( array ); array static void DoubleArray (int[] array) array for (int i = 0; i < array.length; i++) i array[i] *= 2; array = new int[] 2, 4, 6, 8; 12 6 2 4 6 8 1 2 Arrays as Parameters: Summary If an argument of a method is an array, a reference to a array is passed to the method Changing an array element in the method changes the original i An array element can be passed to a method as well, and follow the parameter passing rules of that element's type 1 // ArrayReferenceTest.cs 2 // Testing the effects of passing array references // by value and by reference. 4 using System; Declare and initialize 5 using System.Drawing; 6 using System.Collections; integer array firstarray 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 public class ArrayReferenceTest System.Windows.Forms.Form : 12 1 private System.Windows.Forms.Label outputlabel; 14 private System.Windows.Forms.Button showoutputbutton; 15 16 [STAThread] Declare integer array 17 static void Main() firstarraycopy and have it 18 19 Application.Run( new ArrayReferenceTest() reference firstarray); 20 21 22 private void showoutputbutton_click( object sender, 2 System.EventArgs e ) 25 // create and initialize firstarray 26 int[] firstarray = 1, 2, ; 27 28 // copy firstarray reference 29 int[] firstarraycopy = firstarray; 0 1 outputlabel.text += 2 "Test passing firstarray reference by value"; 4 outputlabel.text += "\n\ncontents of firstarray " + 5 "before calling FirstDouble:\n\t"; ArrayReferenceTe st.cs 6 7 // print contents of firstarray 8 for ( int i = 0; i < firstarray.length; i++ ) 9 outputlabel.text += firstarray[ i ] + " "; ArrayReferenceTe 40 41 // pass reference firstarray by value to FirstDouble st.cs 42 FirstDouble( firstarray ); Test whether firstarray and firstarraycopy 4 44 outputlabel.text += "\n\ncontents of firstarray reference the after same " object + 45 "calling FirstDouble\n\t"; Declare integer array secondarraycopy and 46 47 // print contents of firstarray set it to reference Output secondarray contents of firstarray 48 for ( int i = 0; i < firstarray.length; i++ ) Declare and initialize integer arry 49 outputlabel.text += firstarray[ i ] + " "; secondarray 50 51 // test whether reference was changed by FirstDouble Call method FirstDouble 52 if ( firstarray == firstarraycopy ) on firstarray 5 outputlabel.text t t += 54 "\n\nthe references refer to the same array\n"; 55 else 56 outputlabel.text += 57 "\n\nthe references refer to different arrays\n"; 58 59 // create and initialize secondarray Output contents of firstarray 60 int[] secondarray = 1, 2, ; 61 62 // copy secondarray reference 6 int[] secondarraycopy = secondarray; 64 65 outputlabel.text += "\ntest passing secondarray " + 66 "reference by reference"; 67 68 outputlabel.text += "\n\ncontents of secondarray " + 69 "before calling SecondDouble:\n\t"; 70 71 // print contents of secondarray before method call 72 for ( int i = 0; i < secondarray.length; i++ ) 7 outputlabel.text += secondarray[ i ] + " "; 74 Test whether secondarray ArrayReferenceTe 75 SecondDouble( ref secondarray ); 76 and secondarraycopy 77 outputlabel.text += "\n\ncontents st.cs of reference secondarray the same " + object SecondDouble:\n\t"; 78 "after calling 79 80 // print contents of secondarray after method call Replace each element in the array 81 82 for ( int i = 0; i < secondarray.length; i++ ) outputlabel.text += secondarray[ i ] + " "; Output by twice contents its value of secondarray 8 84 // test whether reference was changed by SecondDouble Set array to reference a new 85 if ( secondarray == secondarraycopy ) integer array containing the 86 outputlabel.text += values Call method 11, 12 and SecondDouble 1 87 88 "\n\nthe references refer to the same array\n"; else and pass secondarray by 89 outputlabel.text += reference 90 "\n\nthe references refer to different arrays\n"; 91 92 // end method showoutputbutton_click Output contents of secondarray 9 94 // modify elements of array and attempt to modify 95 // reference 96 void FirstDouble( int[] array ) 97 98 // double each element's value 99 for ( int i = 0; i < array.length; i++ ) 100 array[ i ] *= 2; 101 102 // create new reference and assign it to array 10 array = new int[] 11, 12, 1 ; 104 105 6

106 // modify elements of array and change reference array 107 // to refer to a new array 108 void SecondDouble( ref int[] array ) 109 110 // double each element's value 111 for ( int i = 0; i < array.length; i++ ) 112 array[ i ] *= 2; 11 114 // create new reference and assign it to array 115 array = new int[] 11, 12, 1 ; 116 117 Set Replace array each to reference element a in new the integer array array containing by twice its the value values 11, 12 and 1 ArrayReferenceTe st.cs Multiple-Subscripted Arrays Require two or more subscripts to identify a particular element Arrays that require two subscripts to identify an element are called double-subscripted arrays Rectangular arrays Often represent tables in which each row is the same size and each column is the same size By convention, first subscript identifies the element s row and the second subscript the element s column Jagged Arrays Arrays of arrays Arrays that compose jagged arrays can be of different lengths 8 Two Types of Double-Subscripted Arrays 9 Multiple-Subscripted Arrays 40 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,, 4, 5, 6 ; int[,] a11 = new int[,4]; jagged arrays arrays of arrays arrays that compose jagged arrays can be of different lengths, e.g., int[][] array2 = new int[ ][]; array2[ 0 ] = new int[] 1, 2 ; array2[ 1 ] = new int[] ; array2[ 2 ] = new int[] 4, 5, 6 ; array2[2][1] = ; Row 0 Row 1 Row 2 Column 0 Column 1 Column 2 Column a[0, 0] a[0, 1] a[0, 2] a[0, ] a[1, 0] a[1, 1] a[1, 2] a[1, ] a[2, 0] a [2, 1] a[2, 2] a[2, ] Column index (or subscript) Row index (or subscript) Array name Double-subscripted array with three rows and four columns. Jagged Arrays 41 Inside a 2D JaggedArray 42 Jagged arrays are "arrays of arrays" Don't require each row to be the same length Similar, but not identical, to Java's 2D arrays Create a 2-row jagged array like this int[][] grid = new int[2][]; // no second value grid[0] = new int[4]; grid[1] = new int[4]; Cannot supply a value for both dimensions at once 7

Using Jagged Arrays Access elements using pairs of brackets grid[1][1] = ; // not grid[1,1] You may pass individual rows to methods average(grid[0]); // declared as int[] Each row may have a different "length" int len = grid[0].length; 4 1 // TwoDimensionalArrays.cs 2 // Initializing two-dimensional arrays. Declare and initialize a using System; rectangular integer array 4 using System.Drawing; named array1 TwoDimensionalAr 5 using System.Collections; 6 using System.ComponentModel; rays.cs 7 using System.Windows.Forms; 8 using System.Data; 9 Declare a jagged 10 public class TwoDimensionalArrays : System.Windows.Forms.Form array named 11 array2 with rows 12 private System.Windows.Forms.Button showoutputbutton; 1 private System.Windows.Forms.Label outputlabel; 14 15 // Visual Studio.NET generated code Initialize the first 16 element in array2 to be 17 [STAThread] an array that contains 18 static ti void Main() two integers 19 20 Application.Run( new TwoDimensionalArrays() ); 21 22 Initialize the second element in 2 private void showoutputbutton_click( object sender, System.EventArgs e ) array2 to be an array that 25 contains 1 integer 26 // declaration and initialization of rectangular array 27 int[,] array1 = new int[,] 1, 2,, 4, 5, 6 ; 28 29 Initialize the third element // declaration and initialization of jagged array in array2 to be an array that 0 int[][] array2 = new int[ ][]; contains integers 1 array2[ 0 ] = new int[] 1, 2 ; 2 array2[ 1 ] = new int[] ; array2[ 2 ] = new int[] 4, 5, 6 ; 4 5 outputlabel.text += "Values in array1 by row are\n"; 6 7 // output values in array1 8 for ( int i = 0; i < array1.length; i++ ) 9 40 for ( int j = 0; j < array1[i].length; j++ ) 41 outputlabel.text += array1[ i, j ] + " "; 42 4 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 ] + " "; 5 54 outputlabel.text += "\n"; 55 56 57 // end method showoutputbutton_click 58 59 // end class TwoDimensionalArrays TwoDimensionalAr rays.cs 1 // DoubleArray.cs 2 // Manipulating a double-subscripted array. 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; 1 private System.Windows.Forms.Label outputlabel; 14 15 int[][] grades; Initialize array grades to have rows 16 int students, exams; 17 18 // Visual Studio.NET generated code Initialize each element in array grades 19 20 [STAThread] 21 static void Main() 22 2 Application.Run( new DoubleArray() ); 25 26 private void showoutputbutton_click( object sender, 27 System.EventArgs e ) 28 29 0 grades = new int[ ][]; 1 grades[ 0 ] = new int[] 77, 68, 86, 7 ; 2 grades[ 1 ] = new int[] 96, 87, 89, 81 ; grades[ 2 ] = new int[] 70, 90, 86, 81 ; 4 DoubleArray.cs 5 students = grades.length; // number of students 6 exams = grades[ 0 ].Length; // number of exams 7 8 // line up column headings Output each row 9 outputlabel.text += " "; DoubleArray.cs 40 41 // output the column headings Output each 42 for ( int i = 0; i < exams; i++ ) element of the row 4 outputlabel.text += "[" + i + "] "; 44 45 // output the rows 46 for ( int i = 0; i < students; i++ ) 47 Output the minimum and 48 outputlabel.text += "\ngrades[" + i + "] "; 49 maximum grades 50 for ( int j = 0; j < exams; j++ ) 51 outputlabel.text += grades[ i ][ j ] + "; Output the average for each row " 52 5 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 6 // 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 ) 7 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 8 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 DoubleArray.cs Examine each element in grades array If the current array element higher then the highest grade, set the value Examine each element of highgrade to be the current in grades array element If the current array element is less then the lowest grade, set the value of lowgrade to be the current element 8

9 // determine average grade for a particular student 94 public double Average( int[] setofgrades ) 95 96 int total = 0; DoubleArray.cs 97 98 for ( int i = 0; i < setofgrades.length; i++ ) 99 total += setofgrades[ i ]; 100 101 return ( double ) total / setofgrades.length; 102 10 Total the grades for the array 104 // end class DoubleArray Divide the total by the number of grades foreach Repetition Structure The foreach repetition structure is used to iterate through values in data structures such as arrays No counter A variable is used to represent the value of each element 50 1 // ForEach.cs 2 // Demonstrating for/each structure. using System; Use the foreach loop to examine 4 each element in the array ForEach.cs 5 class ForEach 6 7 // main entry point for the application If the current array element is smaller 8 static void Main( string[] args ) 9 then lowgrade, set lowgrade to contain 10 int[,] gradearray = 77, 68, 86, 7, the value of the current element 11 98, 87, 89, 81, 70, 90, 86, 81 ; 12 1 int lowgrade = 100; 14 15 foreach ( int grade in gradearray ) 16 17 if ( grade < lowgrade ) 18 lowgrade = grade; 19 20 21 Console.WriteLine( "The minimum grade is: " + lowgrade ); 22 2 Introducing ArrayList The biggest problem with arrays is the fixed size Means you always have to plan for the worst case TheArrayList class is a "growable" array Only holds objects, but primitives are "boxed" All items don't need to be the same type Automatically resizes when needed Part of the System.Collections namespace Includes many sophisticated data structures 52 The minimum grade is: 68 Creating an ArrayList 5 ArrayList Resizing 54 Add a using declaration for System.Collections Create an ArrayList using one of these constructors: ArrayList a1 = new ArrayList(); // 16 items ArrayList a2 = new ArrayList(ar); // size of ar ArrayList a = new ArrayList(1);// 1 item The Capacity of an ArrayList is how many elements that it can hold without resizing itself The Count is how many values it holds An ArrayList will grow as new elements are added Capacity is doubled when the current size is exceeded Use Add() or Insert() to add items to the list Both will automatically expand the list if necessary Insert will move existing items "down" on list To delete items, use Remove() methods List is automatically "closed up" To modify or retrieve elements, use subscripts 9

Other ArrayList Methods ArrayLists can make your code simpler Don't have to explicitly size them Many methods that eliminate "hand-coding" Contains() performs a linear search on the list IndexOf() to retrieve the position of an item (linear) Sort() to order the items (if they are sortable) BinarySearch() to locate a value in a sorted list These last three work on arrays as well Use the methods in the System.Array class 55 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 56 BubbleSorter.cs 1 // BubbleSorter.cs 2 // Sorting an array's values into ascending order. 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; 1 private System.Windows.Forms.Label outputlabel; 14 15 // Visual Studio.NET generated code Declare and initialize array a 16 17 [STAThread] 18 static ti void Main() Output the contents of array a 19 20 Application.Run( new BubbleSorter() ); 21 Call method Bubble sort on array a 22 2 private void sortbutton_click( object sender, System.EventArgs e ) 25 26 int[] a = 2, 6, 4, 8, 10, 12, 89, 68, 45, 7 ; 27 28 outputlabel.text += "Data items in original order\n"; 29 0 for ( int i = 0; i < a.length; i++ ) 1 outputlabel.text += " " + a[ i ]; 2 sort elements in array a // 4 BubbleSort( a ); 5 6 outputlabel.text += "\n\ndata items in ascending order\n"; 7 8 for ( int i = 0; i < a.length; i++ ) 9 outputlabel.text += " " + a[ i ]; Swaps two elements 40 BubbleSorter.cs of an array 41 // end method sortbutton_click If an given element is 42 bigger then the Output following sorted array a 4 // sort the elements of an array with bubble sort element, swap the elements 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 5 54 Perform b.length-1 Perform passes contents of for loop // swap two elements of an array for each element of array b 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 6 Searching Arrays: Linear Search and Binary Search 59 Searching an Array with Linear Search 60 Arrays may be very large Sometimes necessary to determine if a particular element is in the array Linear Search Binary Search Return index of search key in array Begin search at the beginning of array, continue sequentially On average, half the array needs to be searched to find desired element Works well for small or unsorted arrays 10

1 // LinearSearcher.cs 2 // Demonstrating linear searching of an array. using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; Retrieve the number user 7 using System.Windows.Forms; input as the search key 8 using System.Data; 9 10 public class LinearSearcher System.Windows.Forms.Form : 11 12 private System.Windows.Forms.Button searchbutton; 1 private System.Windows.Forms.TextBox inputtextbox; 14 private System.Windows.Forms.Label outputlabel; 15 16 int[] a = 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22,, 26, 17 28, 0, 2, 4, 6, 8, 40, 42, 44, 46, 48, 50 ; 18 19 // Visual Studio.NET generated code 20 21 [STAThread] 22 static void Main() 2 Application.Run( new LinearSearcher() ); 25 26 27 private void searchbutton_click( object sender, 28 System.EventArgs e ) 29 0 int searchkey = Int2.Parse( inputtextbox.text ); 1 2 int elementindex = LinearSearch( a, searchkey ); Perform linear search for the search key LinearSearcher.c s 4 if ( elementindex!= -1 ) 5 outputlabel.text = 6 "Found value in element " + elementindex; 7 LinearSearcher.c 8 else 9 outputlabel.text = "Value not found"; s 40 41 // end method searchbutton_click If the index of the search key is 42 4 // search array for the specified key value 1, then element was not found 44 public int LinearSearch( int[] array, int key ) 45 If search failed, return -1 46 for ( int n = 0; n < array.length; n++ ) 47 48 if ( array[ n ] == key ) Start at beginning of array 49 return n; 50 Check every element to see if it 51 matches the search key. 52 return -1; If it does, return the current index 5 54 // end method LinearSearch 55 56 // end class LinearSearcher Searching a Sorted Array with Binary Search Array must be sorted Eliminate half the search elements at each step Algorithm Locate middle element Compare to search key If they are equal the element has been found, return subscript of middle element If the search key is less then the middle element, search the first half of the array If the search key is greater then the middle element, search the second half of the array Repeat above until search key is equal to the middle element, or the subarray to be searched is on element (in which case the search key is not in the array) 6 1 // BinarySearchTest.cs 2 // Demonstrating a binary search of an array. 4 using System; 5 using System.Drawing; Declare and initialize 6 using System.Collections; integer array a 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 public class BinarySearchTest System.Windows.Forms.Form : 12 1 private System.Windows.Forms.Label promptlabel; 14 15 private System.Windows.Forms.TextBox inputtextbox; 16 17 private System.Windows.Forms.Label resultlabel; 18 private System.Windows.Forms.Label displaylabel; l 19 private System.Windows.Forms.Label outputlabel; 20 21 private System.Windows.Forms.Button findbutton; 22 2 private System.ComponentModel.Container components = null; 25 int[] a = 0, 2, 4, 6, 8, 10, 12, 14, 16, 26 18, 20, 22,, 26, 28 ; 27 28 // Visual Studio.NET generated code 29 0 // main entry point for application 1 [STAThread] 2 static void Main() 4 Application.Run( new BinarySearchTest() ); 5 BinarySearchTest.cs 6 7 // searches for an element by calling 8 // BinarySearch and displaying results 9 private void findbutton_click( object sender, BinarySearchTest 40 System.EventArgs e ) 41.cs 42 int searchkey = Int2.Parse( inputtextbox.text ); 4 44 // initialize display string for the new search If the low index is less then 45 46 outputlabel.text = "Portions of array searched\n"; the high index then try to 47 // perform the binary search find element (otherwise, 48 int element = BinarySearch( a, searchkey ); Retrieve element the search is not key in the the user array input 49 50 if ( element!= -1 ) 51 displaylabel.text = "Found value in element " + Compute midpoint of 52 element; current search space 5 else Call method BinarySearch on 54 displaylabel.text = "Value not found"; array a with the user input as 55 56 // end findbutton_click the search key 57 58 // searchs array for specified key 59 public int BinarySearch( int[] array, int key ) If 1 was returned, then 60 search key was not found 61 int low = 0; // low subscript 62 int high = array.length // high subscript - 1; 6 int middle; // middle subscript 64 65 while ( low <= high ) 66 67 middle = ( low + high 2; ) / 68 69 // the following line displays the portion 70 // of the array currently being manipulated during 71 // each iteration of the binary search loop 72 7 BuildOutput( a, low, middle, high ); BinarySearchTest 74 if ( key == array[ middle ] ) // match.cs 75 return middle; Output all elements of the 76 else if ( key < array[ middle ] ) 77 high = middle - 1; // search low end of array array within two indices and 78 else mark the middle element. 79 80 low = middle + 1; If the middle element matches Print spaces the for the other 81 // end BinarySearch search key, return the index elements of the 82 8 return -1; // search key middle element found not 84 85 // end method BinarySearch If the key value is smaller 86 87 public void BuildOutput( then the middle element, set 88 int[] array, int low, int mid, int high ) the high index to be one less 89 then the current middle index 90 for ( int i = 0; i < array.length; i++ ) 91 92 if ( i < low i > high ) 9 outputlabel.text += " "; Otherwise, set the low index to be 94 95 mark middle element in output one more then the middle index // 96 else if ( i == mid ) 97 outputlabel.text += 98 array[ i ].ToString( "00" ) + "* "; 11

99 else 100 outputlabel.text += 101 array[ i ].ToString( "00" ) + " "; 102 10 104 outputlabel.text += "\n"; 105 106 // end BuildOutput 107 108 // end class BinarySearchTest BinarySearchTest.cs BinarySearchTest.cs 12