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

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

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

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

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

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

C# and.net (1) cont d

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)

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

Flag Quiz Application

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

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.

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CSC 330 Object-Oriented Programming. Encapsulation

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

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

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

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

Chapter 7: Arrays and the ArrayList Class

Object Oriented Programming. Java-Lecture 6 - Arrays

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

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

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

C/C++ Programming Lecture 18 Name:

Multiple-Subscripted Arrays

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

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

CS 106 Introduction to Computer Science I

Example: Computing prime numbers

Computer Science & Engineering 150A Problem Solving Using Computers

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

TOPICS TO COVER:-- Array declaration and use.

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

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

Introduction to Computer Science Midterm 3 Fall, Points

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

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

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

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

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

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

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)

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

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

Chapter 9 Introduction to Arrays. Fundamentals of Java

Chapter 10 - Notes Applications of Arrays

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

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

Arrays and ArrayLists. David Greenstein Monta Vista High School

Computer Programming Lecture 14 Arrays (Part 2)

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

PLD Semester Exam Study Guide Dec. 2018

Student Performance Q&A:

Exam 2. CSC 121 TTH Class. Lecturer: Howard Rosenthal. April 26, 2016

Search,Sort,Recursion

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

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

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

COMP 202. Programming With Arrays

ECE 122. Engineering Problem Solving with Java

Last Class. While loops Infinite loops Loop counters Iterations

Objectives of This Chapter

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

Pace University. Fundamental Concepts of CS121 1

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Lecture 04 FUNCTIONS AND ARRAYS

Instructor: Eng.Omar Al-Nahal

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

More on Arrays CS 16: Solving Problems with Computers I Lecture #13

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

Lecture #8-10 Arrays

Lexical Considerations

CMSC131. Arrays: The Concept

1 Lexical Considerations

Review of Important Topics in CS1600. Functions Arrays C-strings

Lexical Considerations

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

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

CS162: Introduction to Computer Science II

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

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

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

Introduction to Microsoft.NET

Control Statements. Musa M. Ameen Computer Engineering Dept.

Transcription:

CSC 330 Object Oriented Programming Arrays

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

Arrays: Declaration and Instantiation 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]; // 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]; 5

Array: An Array of Simple Values grades grades[ 0 ] grades[ 1 ] grades[ 2 ] grades[ [3] grades[ 4 ] grades[ 5 ] grades[ 6 ] -45 6 0 72 1543-89 0 position number (index or subscript) of the grades[ 7 ] grades[ 8] 62-3 element within array grades grades[ 9 ] 1 grades[ 10 ] 6453 grades[ 11 ] -78 A 12-element array of values. 6

Array: An Array of Objects times times[ 0 ] times[ 1 ] times[ 2 ] times[ 3 ] times[ 4 ] times[ 5 ] times[ 6 ] ref to obj 0 ref to obj 1 ref to obj 2 ref to obj bj3 ref to obj 4 ref to obj 5 ref to obj 6 position number (index times[ 7 ] ref to obj 7 or subscript) of the times[ 8] ref to obj 8 element within array times times[ 9 ] ref to obj 9 A 10-element array of objects 7

Summary of Operators 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 ihtto left assignment Precedence and associativity of the operators discussed so far. 8

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 9

Array: Length Each array has a public property p 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 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 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 11

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, 323, 89, 933, 540}; char[] lettergrades = {'A', 'B', 'C', 'D', 'F'}; string[] wordlist = { cs112, computer", television"}; 12

1 // InitArray.cs 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 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 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 a constant ARRAY_SIZE Declare z Outline InitArray.cs Create an array of size ARRAY_SIZE; z is a reference to it. Initialize the elements in z using a for loop

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"; Outline 38 InitArray.cs 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 Program Output

1 // SumArray.cs 2 // Computing the sum of the elements in an array. 3 5 using System.Windows.Forms; 6 7 class SumArray 8 { 9 // main entry point for application Outline 4 using System; Declare integer array a SumArray.cs and initialize it 10 static void Main( string[] args ) 11 { 12 int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 13 int total = 0; 14 Total the contents of array a 15 for ( int i = 0; i < a.length; i++ ) 16 total += a[ i ]; 17 18 MessageBox.Show( "Total of array elements: " + total, 19 "Sum the elements of an array", 20 MessageBoxButtons.OK, 21 MessageBoxIcon.Information ); 22 23 } // end Main 24 25 } // end class SumArray Program Output

Recall: Two Types of Variables A variable represents a cell in memory x 45 Value type int, char, byte, float, double, string A value type variable stores a value of the y 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.12 t1 11 45 59 16

Implications of the Two Types of Variables: Assignment An assignment of one value variable to x 45 another value variable copies the value, e.g., int x = 45; double y = 45.12; int z; z = x; y z 45 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; 45.12 t1 11 45 59 t2 17

Implications of the Two Types of Variables: Change x 23 Change the value of one value variable 45 23 will not change the other: int x = 45; double y = 45.12; y 45.12 int z; z = x; z 45 x = 23; Change the content (state) by one reference may affect another reference variable Time3 t1; t1 = new Time3(11, 45, 59); t1 22 11 45 22 Time3 t2; 59 22 t2 = t1; t2.settime(22, 22, 22); t2 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 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 19

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 int num = SquareSum (2, 3); static int SquareSum (int num1, int num2) { } num1 = num1 + num2; return num1 * num1; num1 25 num2 3 20

Calling a Method: Value Type int n1 = 2; int n2 = 3; int num = SquareSum (n1, n2); n1 n2 2 3 static int SquareSum (int num1, int num2) { } num1 = num1 + num2; return num1 * num1; num1 25 num2 3 21

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 num1 = 2; num1 2 int num2 = 3; num2 int num = SquareSum (num1, num2); 3 static int SquareSum (int num1, int num2) { num1 = num1 + num2; return num1 * num1; num1 25 } num2 3 22

Calling a Method: Using ref/out 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 25 int n1 = 2; n2 3 int n2 = 3; num 25 int num = SquareSum (ref n1, ref n2); static int SquareSum (ref int num1, ref int num2) { num1 = num1 + num2; return num1 * num1; } 23

Passing Arrays to Methods What happens when you pass an array variable to a method? [Assume a variable named nums is original array] 24

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]; i for (int i = 0; i < size; i++) copy[ i ] = ar[ i ]; Problem is, that this is fairly slow and tedious 27

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 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 lvariable, and dthen 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, 3}; array DoubleArray (array); static void DoubleArray (int[] array) { } for (int i = 0; i < array.length; i++) array[i] *= 2; array 12 24 36 30

Calling a Method: Side Effect of Reference If an argument is a reference type, then modifying the content/state of the array/object through h the reference will have side effect int[] array = {1, 2, 3}; array DoubleArray (array); static void DoubleArray (int[] array) { } array for (int i = 0; i < array.length; i++) i array[i] *= 2; 12 24 36 31

Calling a Method: 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, 3}; array DoubleArray( 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 24 36 2 4 6 8 32

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 An array element can be passed to a method as well, and follow the parameter passing rules of that element's type 33

1 // ArrayReferenceTest.cs 2 // Testing the effects of passing array references 3 // by value and by reference. 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 public class ArrayReferenceTest : System.Windows.Forms.Form 12 { 13 private System.Windows.Forms.Label outputlabel; 14 private System.Windows.Forms.Button showoutputbutton; 15 16 [STAThread] 17 static void Main() 18 { 19 Application.Run( new ArrayReferenceTest() ); Outline Declare and initialize iti ArrayReferenceTe integer array firstarray st.cs Declare integer array firstarraycopy and have it reference firstarray 20 } 21 22 private void showoutputbutton_click( object sender, 23 System.EventArgs e ) 24 { 25 // create and initialize firstarray 26 int[] firstarray = { 1, 2, 3 }; 27 28 // copy firstarray reference 29 int[] firstarraycopy = firstarray; 30 31 outputlabel.text += 32 "Test passing firstarray reference by value"; 33 34 outputlabel.text += "\n\ncontents of firstarray " + 35 "before calling FirstDouble:\n\t";

36 37 // print contents of firstarray 38 for ( int i = 0; i < firstarray.length; i++ ) 39 outputlabel.text += firstarray[ i ] + " "; 40 41 // pass reference firstarray by value to FirstDouble 42 FirstDouble( firstarray ); 43 44 outputlabel.text += "\n\ncontents of firstarray after " + 45 "calling FirstDouble\n\t"; \ 46 47 // print contents of firstarray 48 for ( int i = 0; i < firstarray.length; i++ ) 49 outputlabel.text += firstarray[ i ] + " "; 50 51 // test whether reference was changed by FirstDouble 52 if ( firstarray == firstarraycopy ) 53 outputlabel.text += 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 60 int[] secondarray = { 1, 2, 3 }; 61 62 // copy secondarray reference 63 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 Outline ArrayReferenceTe st.cs Test whether firstarray and firstarraycopy reference the same object Declare integer array secondarraycopy and set it to reference Output secondarray contents of firstarray Declare and initialize integer arry secondarray Cll Call method hdfirstdouble on firstarray Output contents of firstarray

71 // print contents of secondarray before method call 72 for ( int i = 0; i < secondarray.length; i++ ) 73 outputlabel.text += secondarray[ i ] + " "; 74 75 SecondDouble( ref secondarray ); 76 77 outputlabel.text += "\n\ncontents of secondarray " + 78 "after calling SecondDouble:\n\t"; 79 80 // print contents of secondarray after method call 81 for ( int i = 0; i < secondarray.length; i++ ) 82 outputlabel.text += secondarray[ i ] + " "; 83 84 // test whether reference was changed by SecondDouble 85 if ( secondarray == secondarraycopy ) 86 outputlabel.text += 87 "\n\nthe references refer to the same array\n"; 88 else 89 outputlabel.text += 90 "\n\nthe references refer to different arrays\n"; 91 92 } // end method showoutputbutton_click 93 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 103 array = new int[] { 11, 12, 13 }; 104 } 105 Outline Test whether secondarray ArrayReferenceTe and secondarraycopy st.cs reference the same object Replace each element in the array Output by twice contents its value of secondarray Set array to reference a new integer array containing the values Call method 11, 12 and SecondDouble 13 and pass secondarray by reference Output contents of secondarray

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; 113 114 // create new reference and assign it to array 115 array = new int[] { 11, 12, 13 }; 116 } 117 } Set Replace array to each reference element a in new the integer array array containing by twice its the value values 11, 12 and 13 Outline ArrayReferenceTe st.cs Program Output t

Multiple-Subscripted Arrays 38 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 darrays Arrays of arrays Arrays that compose jagged arrays can be of different lengths

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

Multiple-Subscripted Arrays 40 Row 0 Row 1 Column 0 Column 1 Column 2 Column 3 a[0, 0] a[0, 1] a[0, 2] a[0, 3] a[1, 0] a[1, 1] a[1, 2] a[1, 3] Row 2 a[2, 0] a [2, 1] a[2, 2] a[2, 3] Column index (or subscript) Row index (or subscript) Array name Double-subscripted array with three rows and four columns.

Jagged Arrays 41 Ragged 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 ragged 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

Inside a 2D JaggedArray 42

Using Jagged Arrays 43 Access elements using pairs of brackets grid[1][1] = 3; // not grid[1,1] You may ypass individual rows to methods average(grid[0]); // declared as int[] Each row may have a different "length" int len = grid[0].length;

1 // TwoDimensionalArrays.cs 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 Declare and initialize a rectangular integer array named array1 10 public class TwoDimensionalArrays i : 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 iti 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"; Outline TwoDimensionalAr rays.cs 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

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 Outline TwoDimensionalAr rays.cs Program Output

1 // DoubleArray.cs 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 int[][] grades; 16 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( tb tt 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 i array grades to have 3 rows Initialize each element in array grades Outline DoubleArray.cs

35 students = grades.length; // number of students 36 exams = grades[ 0 ].Length; // number of exams 37 Outline 38 // line up column headings Output each row DoubleArray.cs 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() + Output each element of the row 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 the minimum and maximum grades Output the average for each row

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 } Outline DoubleArray.cs Examine each element in grades array If the current array element higher then the highest grade, set the value 77 Examine each element of highgrade to be the current in grades array element 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 hg = grades[ i ][ j ]; 89 90 return highgrade; 91 } 92 If the current array element is less then the lowest grade, set the value of lowgrade to be the current element

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 Divide the total by the number of grades Total the grades for the array Outline DoubleArray.cs Program Output

50 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

1 // ForEach.cs 2 // Demonstrating for/each structure. 3 using System; 4 each element in the array 5 class ForEach 6 { 7 // main entry point for the application 8 static void Main( string[] args ) 9 { 10 int[,] gradearray = { { 77, 68, 86, 73 }, 11 { 98, 87, 89, 81 }, { 70, 90, 86, 81 } }; 12 13 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 } 23 } Use the foreach loop to examine Outline ForEach.cscs If the current array element is smaller then lowgrade, set lowgrade to contain the value of the current element The minimum grade is: 68

52 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

Creating an ArrayList 53 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 a3 = 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

54 ArrayList Resizing 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

Other ArrayList Methods 55 ArrayLists can make your code simpler Don't have to explicitly size them Many methods that eliminate "hand-coding" Contains() Contains() performs a linear search on the list IndexOf() IndexOf() to retrieve the position of an item (linear) Sort() to order the items (if they are sortable) Sort() BinarySearch() to locate a value in a sorted dlist BinarySearch() These last three work on arrays as well Use the methods in the System.Array System.Array class

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 l.net Framework includes high-speed sorting capabilities 56

1 // 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 Declare and initialize array a 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 Output the contents of array a Outline BubbleSorter.cs Call method Bubble sort on array a

36 outputlabel.text += "\n\ndata items in ascending order\n"; 37 38 for ( int i = 0; i < a.length; i++ ) Outline 39 outputlabel.text += " " + a[ i ]; Swaps two elements BubbleSorter.cs 40 of an array 41 } // end method sortbutton_click If an given element is 42 bigger then the Output following sorted array a 43 // 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 } 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 } Perform b.length-1 Perform passes contents of for loop for each element of array b Program Output

Searching Arrays: Linear Search and Binary Search 59 Arrays may be very large Sometimes necessary to determine if a particular element is in the array Linear Search Binary Search

Searching an Array with Linear Search 60 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

1 // LinearSearcher.cs 2 // Demonstrating linear searching of an 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 Retrieve the number user input as the search key 10 public class LinearSearcher : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button searchbutton; 13 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, 24, 26, 17 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50 }; 18 19 // Visual Studio.NET generated code 20 21 [STAThread] 22 static void Main() 23 { 24 Application.Run( new LinearSearcher() ); 25 } 26 27 private void searchbutton_click( object sender, 28 System.EventArgs e ) 29 { 30 int searchkey = Int32.Parse( inputtextbox.text ); 31 32 int elementindex = LinearSearch( a, searchkey ); 33 Perform linear search for the search key Outline LinearSearcher.cc s

34 if ( elementindex!= -1 ) 35 outputlabel.text = 36 "Found value in element " + elementindex; 37 38 else 39 outputlabel.text = "Value not found"; 40 41 } // end method searchbutton_click 42 43 // search array for the specified key value 44 public int LinearSearch( int[] array, int key ) 45 { 46 for ( int n = 0; n < array.length; n++ ) 47 { 48 if ( array[ n ] == key ) 49 return n; 50 } 51 52 return -1; 53 54 } // end method LinearSearch 55 56 } // end class LinearSearcher If the index of the search key is 1, then element was not found If search failed, return -1 Start at beginning i of array Check every element to see if it matches the search key. If it does, return the current index Outline LinearSearcher.cc s Program Output

Searching a Sorted Array with Binary Search 63 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 h case the search key is not in the array)

1 // BinarySearchTest.cs 2 // Demonstrating a binary search of an array. 3 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; Declare and initialize integer array a 10 11 public class BinarySearchTest : System.Windows.Forms.Form 12 { 13 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; 19 private System.Windows.Forms.Label outputlabel; 20 21 private System.Windows.Forms.Button findbutton; 22 23 private System.ComponentModel.Container components = null; 24 25 int[] a = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 26 18, 20, 22, 24, 26, 28 }; 27 28 // Visual Studio.NET generated code 29 30 // main entry point for application 31 [STAThread] 32 static void Main() 33 { 34 Application.Run( new BinarySearchTest() ); 35 } Outline BinarySearchTest.cs

36 37 // searches for an element by calling 38 // BinarySearch and displaying results 39 private void findbutton_ Click( object sender, 40 System.EventArgs e ) 41 { 42 int searchkey = Int32.Parse( inputtextbox.text ); 43 44 // initialize display string for the new search 45 outputlabel.text = "Portions of array searched\n"; 46 47 // perform the binary search 48 int element = BinarySearch( a, searchkey ); 49 50 if ( element!= -1 ) 51 displaylabel.text = "Found value in element " + 52 element; 53 else 54 displaylabel.text = "Value not found"; 55 56 } // end findbutton_click 57 58 // searchs array for specified key 59 public int BinarySearch( int[] array, int key ) 60 { 61 int low = 0; // low subscript 62 int high = array.length - 1; // high subscript 63 int middle; // middle subscript 64 65 while ( low <= high ) 66 { 67 middle = ( low + high ) / 2; 68 Outline BinarySearchTest.cs If the low index is less then the high index then try to find element (otherwise, Retrieve element the search is not key in the the user array input Compute midpoint of current search space Call method BinarySearch on array a with the user input as the search key If 1 was returned, then search key was not found

69 // the following line displays the portion 70 // of the array currently being manipulated during 71 // each iteration of the binary search loop 72 BuildOutput( a, low, middle, high ); 73 74 if ( key == array[ middle ] ) // match 75 return middle; 76 else if ( key < array[ middle ] ) 77 high = middle - 1; // search low end of array 78 else 79 low = middle + 1; 80 81 } // end BinarySearch 82 83 return -1; // search key not found 84 85 } // end method BinarySearch 86 87 public void BuildOutput( 88 int[] array, int low, int mid, int high ) 89 { 90 for ( int i = 0; i < array.length; i++ ) 91 { 92 if ( i < low i > high ) 93 outputlabel.text += " "; 94 95 // mark middle element in output 96 else if ( i == mid ) 97 outputlabel.text += 98 array[ i ].ToString( "00" ) + "* "; Outline BinarySearchTest.cs Output all elements of the array within two indices and mark the middle element. If the middle element matches Print spaces the for the other search key, return the index elements of the middle element If the key value is smaller then the middle element, set the high index to be one less then the current middle index Otherwise, set the low index to be one more then the middle index

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

Outline BinarySearchTest.cs Program Output