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

Size: px
Start display at page:

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

Transcription

1 CSC 330 Object Oriented Programming Arrays

2 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

3 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

4 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

5 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

6 Array: An Array of Simple Values grades grades[ 0 ] grades[ 1 ] grades[ 2 ] grades[ [3] grades[ 4 ] grades[ 5 ] grades[ 6 ] 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

7 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

8 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

9 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

10 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

11 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

12 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

13 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 = ""; 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 // 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 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

14 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 ); } // end Main } // end class InitArray Add values in the arrays to output Program Output

15 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 ]; MessageBox.Show( "Total of array elements: " + total, 19 "Sum the elements of an array", 20 MessageBoxButtons.OK, 21 MessageBoxIcon.Information ); } // end Main } // end class SumArray Program Output

16 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); t

17 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; t t2 17

18 Implications of the Two Types of Variables: Change x 23 Change the value of one value variable will not change the other: int x = 45; double y = 45.12; y 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); t Time3 t2; t2 = t1; t2.settime(22, 22, 22); t2 18

19 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

20 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

21 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

22 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

23 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

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

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

26 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

27 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

28 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

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

30 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

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

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

33 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

34 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; public class ArrayReferenceTest : System.Windows.Forms.Form 12 { 13 private System.Windows.Forms.Label outputlabel; 14 private System.Windows.Forms.Button showoutputbutton; [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 } private void showoutputbutton_click( object sender, 23 System.EventArgs e ) 24 { 25 // create and initialize firstarray 26 int[] firstarray = { 1, 2, 3 }; // copy firstarray reference 29 int[] firstarraycopy = firstarray; outputlabel.text += 32 "Test passing firstarray reference by value"; outputlabel.text += "\n\ncontents of firstarray " + 35 "before calling FirstDouble:\n\t";

35 36 37 // print contents of firstarray 38 for ( int i = 0; i < firstarray.length; i++ ) 39 outputlabel.text += firstarray[ i ] + " "; // pass reference firstarray by value to FirstDouble 42 FirstDouble( firstarray ); outputlabel.text += "\n\ncontents of firstarray after " + 45 "calling FirstDouble\n\t"; \ // print contents of firstarray 48 for ( int i = 0; i < firstarray.length; i++ ) 49 outputlabel.text += firstarray[ i ] + " "; // 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"; // create and initialize secondarray 60 int[] secondarray = { 1, 2, 3 }; // copy secondarray reference 63 int[] secondarraycopy = secondarray; outputlabel.text += "\ntest passing secondarray " + 66 "reference by reference"; 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

36 71 // print contents of secondarray before method call 72 for ( int i = 0; i < secondarray.length; i++ ) 73 outputlabel.text += secondarray[ i ] + " "; SecondDouble( ref secondarray ); outputlabel.text += "\n\ncontents of secondarray " + 78 "after calling SecondDouble:\n\t"; // print contents of secondarray after method call 81 for ( int i = 0; i < secondarray.length; i++ ) 82 outputlabel.text += secondarray[ i ] + " "; // 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"; } // end method showoutputbutton_click // 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; // 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

37 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; // 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

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

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

41 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

42 Inside a 2D JaggedArray 42

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

44 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; // 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 iti 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"; 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

45 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 ] + " "; 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 Outline TwoDimensionalAr rays.cs Program Output

46 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; int[][] grades; 16 int students, exams; // Visual Studio.NET generated code [STAThread] 21 static void Main() 22 { 23 Application.Run( new DoubleArray() ); 24 } private void showoutputbutton_click( tb tt 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 i array grades to have 3 rows Initialize each element in array grades Outline DoubleArray.cs

47 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 += " "; // 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() + Output each element of the row 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 the minimum and maximum grades Output the average for each row

48 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 } 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; for ( int i = 0; i < students; i++ ) for ( int j = 0; j < exams; j++ ) if ( grades[ i ][ j ] > highgrade ) 88 highgrade hg = grades[ i ][ j ]; 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

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

50 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

51 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 } }; int lowgrade = 100; foreach ( int grade in gradearray ) 16 { 17 if ( grade < lowgrade ) 18 lowgrade = grade; 19 } 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 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

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

55 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

56 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

57 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; // Visual Studio.NET generated code Declare and initialize array a [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 Output the contents of array a Outline BubbleSorter.cs Call method Bubble sort on array a

58 36 outputlabel.text += "\n\ndata items in ascending order\n"; 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 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 } Perform b.length-1 Perform passes contents of for loop for each element of array b Program Output

59 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

60 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

61 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; 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 }; // Visual Studio.NET generated code [STAThread] 22 static void Main() 23 { 24 Application.Run( new LinearSearcher() ); 25 } private void searchbutton_click( object sender, 28 System.EventArgs e ) 29 { 30 int searchkey = Int32.Parse( inputtextbox.text ); int elementindex = LinearSearch( a, searchkey ); 33 Perform linear search for the search key Outline LinearSearcher.cc s

62 34 if ( elementindex!= -1 ) 35 outputlabel.text = 36 "Found value in element " + elementindex; else 39 outputlabel.text = "Value not found"; } // end method searchbutton_click // 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 } return -1; } // end method LinearSearch } // 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

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

64 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 public class BinarySearchTest : System.Windows.Forms.Form 12 { 13 private System.Windows.Forms.Label promptlabel; private System.Windows.Forms.TextBox inputtextbox; private System.Windows.Forms.Label resultlabel; 18 private System.Windows.Forms.Label displaylabel; 19 private System.Windows.Forms.Label outputlabel; private System.Windows.Forms.Button findbutton; private System.ComponentModel.Container components = null; int[] a = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 26 18, 20, 22, 24, 26, 28 }; // Visual Studio.NET generated code // main entry point for application 31 [STAThread] 32 static void Main() 33 { 34 Application.Run( new BinarySearchTest() ); 35 } Outline BinarySearchTest.cs

65 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 ); // initialize display string for the new search 45 outputlabel.text = "Portions of array searched\n"; // perform the binary search 48 int element = BinarySearch( a, searchkey ); if ( element!= -1 ) 51 displaylabel.text = "Found value in element " + 52 element; 53 else 54 displaylabel.text = "Value not found"; } // end findbutton_click // 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 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

66 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 ); 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; } // end BinarySearch return -1; // search key not found } // end method BinarySearch 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 += " "; // 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

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

68 Outline BinarySearchTest.cs Program Output

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

Arrays. Arrays: Declaration and Instantiation. Array: An Array of Simple Values 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)

More information

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

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd El-Shorouk Academy Acad. Year : 2013 / 2014 High Institute of Computer Science & Information Technology Term : 1 st Year : 2 nd Computer Science Department Object Oriented Programming Section (1) Arrays

More information

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

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type Array Arrays Introduction Group of contiguous memory locations Each memory location has same name Each memory location has same type Remain same size once created Static entries 1 Name of array (Note that

More information

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) Chapter - Arrays 1.1 Introduction 2.1 Introduction.2 Arrays.3 Declaring Arrays. Examples Using Arrays.5 Passing Arrays to Functions.6 Sorting Arrays. Case Study: Computing Mean, Median and Mode Using Arrays.8

More information

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

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types Chapter 4 - Arrays 1 4.1 Introduction 4.2 Arrays 4.3 Declaring Arrays 4.4 Examples Using Arrays 4.5 Passing Arrays to Functions 4.6 Sorting Arrays 4.7 Case Study: Computing Mean, Median and Mode Using

More information

C# and.net (1) cont d

C# and.net (1) cont d C# and.net (1) cont d Acknowledgements and copyrights: these slides are a result of combination of notes and slides with contributions from: Michael Kiffer, Arthur Bernstein, Philip Lewis, Hanspeter Mφssenbφck,

More information

C++ PROGRAMMING SKILLS Part 4: Arrays

C++ PROGRAMMING SKILLS Part 4: Arrays C++ PROGRAMMING SKILLS Part 4: Arrays Outline Introduction to Arrays Declaring and Initializing Arrays Examples Using Arrays Sorting Arrays: Bubble Sort Passing Arrays to Functions Computing Mean, Median

More information

C Arrays Pearson Education, Inc. All rights reserved.

C Arrays Pearson Education, Inc. All rights reserved. 1 6 C Arrays 2 Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end:

More information

Tutorial 5 Completing the Inventory Application Introducing Programming

Tutorial 5 Completing the Inventory Application Introducing Programming 1 Tutorial 5 Completing the Inventory Application Introducing Programming Outline 5.1 Test-Driving the Inventory Application 5.2 Introduction to C# Code 5.3 Inserting an Event Handler 5.4 Performing a

More information

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

Tutorial 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and Arithmetic Tutorial 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and Arithmetic Outline 6.1 Test-Driving the Enhanced Inventory Application 6.2 Variables 6.3 Handling the TextChanged

More information

Arrays (Deitel chapter 7)

Arrays (Deitel chapter 7) Arrays (Deitel chapter 7) Plan Arrays Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods Sorting Arrays Searching Arrays: Linear Search and

More information

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

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on: Arrays Arrays Arrays are objects that help us organize large amounts of information Chapter 7 focuses on: array declaration and use bounds checking and capacity arrays that store object references variable

More information

Flag Quiz Application

Flag Quiz Application T U T O R I A L 17 Objectives In this tutorial, you will learn to: Create and initialize arrays. Store information in an array. Refer to individual elements of an array. Sort arrays. Use ComboBoxes to

More information

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

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays 4 Examples Using Arrays 5 Passing Arrays to Functions 6 Sorting Arrays 7 Case Study: Computing Mean, Median and Mode Using Arrays 8 Searching Arrays

More information

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

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 6 Arrays Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 Chapter 6 - Arrays 6.1 Introduction 6.2 Arrays 6.3 Declaring Arrays 6.4 Examples Using Arrays

More information

Chapter 6: Using Arrays

Chapter 6: Using Arrays Chapter 6: Using Arrays Declaring an Array and Assigning Values to Array Array Elements A list of data items that all have the same data type and the same name Each item is distinguished from the others

More information

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

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved. 1 Chapter 6 Arrays and Strings Introduction 2 Arrays Data structures Related data items of same type Reference type Remain same size once created Fixed-length entries 3 Name of array (note that all elements

More information

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad CHAPTER 3 ARRAYS Dr. Shady Yehia Elmashad Outline 1. Introduction 2. Arrays 3. Declaring Arrays 4. Examples Using Arrays 5. Multidimensional Arrays 6. Multidimensional Arrays Examples 7. Examples Using

More information

CSC 330 Object-Oriented Programming. Encapsulation

CSC 330 Object-Oriented Programming. Encapsulation CSC 330 Object-Oriented Programming Encapsulation Implementing Data Encapsulation using Properties Use C# properties to provide access to data safely data members should be declared private, with public

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

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

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables 1 6 C Arrays 6.2 Arrays 2 Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name + position number arrayname[ position number ] First element at position

More information

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

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

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

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved. Arrays 1 Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Multidimensional Arrays 2 Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column

More information

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

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 7/e This chapter serves as an introduction to data structures. Arrays are data structures consisting of related data items of the same type. In Chapter 10, we discuss C s notion of

More information

Chapter 7: Arrays and the ArrayList Class

Chapter 7: Arrays and the ArrayList Class Chapter 7: Arrays and the ArrayList Class Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 7 discusses the following main topics: Introduction

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays jhtp5_07.fm Page 279 Wednesday, November 20, 2002 12:44 PM 7 Arrays Objectives To introduce the array data structure. To understand the use of arrays to store, sort and search lists and tables of values.

More information

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

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper

More information

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

Fall Semester (081) Dr. El-Sayed El-Alfy Computer Science Department King Fahd University of Petroleum and Minerals INTERNET PROTOCOLS AND CLIENT-SERVER PROGRAMMING Client SWE344 request Internet response Fall Semester 2008-2009 (081) Server Module 2.1: C# Programming Essentials (Part 1) Dr. El-Sayed El-Alfy Computer

More information

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

Polymorphism. Polymorphism. CSC 330 Object Oriented Programming. What is Polymorphism? Why polymorphism? Class-Object to Base-Class. Polymorphism CSC 0 Object Oriented Programming Polymorphism is considered to be a requirement of any true -oriented programming language (OOPL). Reminder: What are the other two essential elements in OOPL?

More information

Data Types. Operators, Assignment, Output and Return Statements

Data Types. Operators, Assignment, Output and Return Statements Pseudocode Reference Sheet rev 4/17 jbo Note: This document has been developed by WeTeach_CS, and is solely based on current study materials and practice tests provided on the TEA website. An official

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

Multiple-Subscripted Arrays

Multiple-Subscripted Arrays Arrays in C can have multiple subscripts. A common use of multiple-subscripted arrays (also called multidimensional arrays) is to represent tables of values consisting of information arranged in rows and

More information

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Chapter 6 SINGLE-DIMENSIONAL ARRAYS Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk What is an Array? A single array variable can reference

More information

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

Class C{ int a; } what variables below are objects : a. C c; b. String str; c. Scanner scanner; d. int num; e. float f; Class C{ int a; } what variables below are objects : a. C c; b. String str; c. Scanner scanner; d. int num; e. float f; Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 11 / 2015 Instructor: Michael Eckmann Today s Topics Comments and/or Questions? Sorting Searching Michael Eckmann - Skidmore College - CS 106 - Summer 2015

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

More information

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science & Engineering 150A Problem Solving Using Computers Computer Science & Engineering 150A Problem Solving Using Computers Lecture 06 - Stephen Scott Adapted from Christopher M. Bourke 1 / 30 Fall 2009 Chapter 8 8.1 Declaring and 8.2 Array Subscripts 8.3 Using

More information

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Review what an array is Review how to declare arrays Review what reference variables are Review how to pass arrays to methods Review

More information

TOPICS TO COVER:-- Array declaration and use.

TOPICS TO COVER:-- Array declaration and use. ARRAYS in JAVA TOPICS TO COVER:-- Array declaration and use. One-Dimensional Arrays. Passing arrays and array elements as parameters Arrays of objects Searching an array Sorting elements in an array ARRAYS

More information

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

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]

More information

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

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays) In this lecture, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of

More information

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

More information

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

Arrays and Collections. C# Programming: From Problem Analysis to Program Design 2nd Edition. David McDonald, Ph.D. Director of Emerging Technologies 7 Arrays and Collections C# Programming: From Problem Analysis to Program Design 2nd Edition David McDonald, Ph.D. Director of Emerging Technologies Chapter Objectives Learn array basics Declare arrays

More information

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

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017 Your Name: Exam 2. CSC 121 MW Class Lecturer: Howard Rosenthal April 26, 2017 The following questions (or parts of questions) in numbers 1-7 are all worth 3 points each. 1. Answer the following as true

More information

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

Last Class. More on loops break continue A bit on arrays Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };

More information

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

Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects 1 Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects Outline 19.1 Test-Driving the Microwave Oven Application 19.2 Designing the Microwave Oven Application 19.3 Adding a New

More information

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved. Data structures Collections of related data items. Discussed in depth in Chapters 16 21. Array objects Data

More information

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

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7) Array Basics: Outline Arrays (Savitch, Chapter 7) TOPICS Array Basics Arrays in Classes and Methods Programming with Arrays Searching and Sorting Arrays Multi-Dimensional Arrays Static Variables and Constants

More information

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

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by Addison-Wesley

More information

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

Classes in C# namespace classtest { public class myclass { public myclass() { } } } Classes in C# A class is of similar function to our previously used Active X components. The difference between the two is the components are registered with windows and can be shared by different applications,

More information

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

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 6: Arrays Arrays An array is an ordered list of values Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking The

More information

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

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator: Chapter 7: 7.1 Arrays Arrays Hold Multiple Values Arrays Hold Multiple Values Array - Memory Layout A single variable can only hold one value int test; 95 Enough memory for 1 int What if we need to store

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

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

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 25, 2016 Your Name: Exam 2. CSC 121 MW Class Lecturer: Howard Rosenthal April 25, 2016 The following questions (or parts of questions) in numbers 1-7 are all worth 3 points each. 1. Answer the following as true

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Chapter 9 Introduction to Arrays. Fundamentals of Java

Chapter 9 Introduction to Arrays. Fundamentals of Java Chapter 9 Introduction to Arrays Objectives Write programs that handle collections of similar items. Declare array variables and instantiate array objects. Manipulate arrays with loops, including the enhanced

More information

Chapter 10 - Notes Applications of Arrays

Chapter 10 - Notes Applications of Arrays Chapter - Notes Applications of Arrays I. List Processing A. Definition: List - A set of values of the same data type. B. Lists and Arrays 1. A convenient way to store a list is in an array, probably a

More information

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

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries CBOP3203 Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries A 12 element Array Index Also called subscript Position number in square brackets Must

More information

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science Department Lecture 3: C# language basics Lecture Contents 2 C# basics Conditions Loops Methods Arrays Dr. Amal Khalifa, Spr 2015 3 Conditions and

More information

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

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 1 ARRAYS Arrays 2 Arrays Structures of related data items Static entity (same size

More information

Array. Arrays. Declaring Arrays. Using Arrays

Array. Arrays. Declaring Arrays. Using Arrays Arrays CS215 Peter Lo 2004 1 Array Array Group of consecutive memory locations Same name and type To refer to an element, specify Array name Position number Format: arrayname[ position number] First element

More information

Arrays and ArrayLists. David Greenstein Monta Vista High School

Arrays and ArrayLists. David Greenstein Monta Vista High School Arrays and ArrayLists David Greenstein Monta Vista High School Array An array is a block of consecutive memory locations that hold values of the same data type. Individual locations are called array s

More information

Computer Programming Lecture 14 Arrays (Part 2)

Computer Programming Lecture 14 Arrays (Part 2) Computer Programming Lecture 14 Arrays (Part 2) Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical & Electronics Engineering nukhet.ozbek@ege.edu.tr 1 Topics The relationship between

More information

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

PLD Semester Exam Study Guide Dec. 2018

PLD Semester Exam Study Guide Dec. 2018 Covers material from Chapters 1-8. Semester Exam will be built from these questions and answers, though they will be re-ordered and re-numbered and possibly worded slightly differently than on this study

More information

Student Performance Q&A:

Student Performance Q&A: Student Performance Q&A: 2016 AP Computer Science A Free-Response Questions The following comments on the 2016 free-response questions for AP Computer Science A were written by the Chief Reader, Elizabeth

More information

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

Exam 2. CSC 121 TTH Class. Lecturer: Howard Rosenthal. April 26, 2016 Your Name: Exam 2. CSC 121 TTH Class Lecturer: Howard Rosenthal April 26, 2016 The following questions (or parts of questions) in numbers 1-7 are all worth 3 points each. 1. Answer the following as true

More information

Search,Sort,Recursion

Search,Sort,Recursion Search,Sort,Recursion Searching, Sorting and Recursion Searching Linear Search Inserting into an Array Deleting from an Array Selection Sort Bubble Sort Binary Search Recursive Binary Search Searching

More information

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

Chapter 6: Arrays. Starting Out with Games and Graphics in C++ Second Edition. by Tony Gaddis Chapter 6: Arrays Starting Out with Games and Graphics in C++ Second Edition by Tony Gaddis 6.1 Array Basics An array allows you to store a group of items of the same data type together in memory Why?

More information

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

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 ARRAYS ~ VECTORS KOM3191 Object-Oriented Computer Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 What is an array? Arrays

More information

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

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF -  1 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 06: Arrays Instructor: AbuKhleif, Mohammad Noor Sep 2017 AbuKhleiF - 1 Instructor AbuKhleif, Mohammad Noor Computer Engineer

More information

COMP 202. Programming With Arrays

COMP 202. Programming With Arrays COMP 202 Programming With Arrays CONTENTS: Arrays, 2D Arrays, Multidimensional Arrays The Array List Variable Length parameter lists The Foreach Statement Thinking Like A Programmer: Designing for arrays

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 10 For Loops and Arrays Outline Problem: How can I perform the same operations a fixed number of times? Considering for loops Performs same operations

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Objectives of This Chapter

Objectives of This Chapter Chapter 6 C Arrays Objectives of This Chapter Array data structures to represent the set of values. Defining and initializing arrays. Defining symbolic constant in a program. Using arrays to store, list,

More information

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

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays A First Book of ANSI C Fourth Edition Chapter 8 Arrays Objectives One-Dimensional Arrays Array Initialization Arrays as Function Arguments Case Study: Computing Averages and Standard Deviations Two-Dimensional

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand what an array is Understand how to declare arrays Understand what reference variables are Understand how to pass arrays to methods

More information

Lecture 04 FUNCTIONS AND ARRAYS

Lecture 04 FUNCTIONS AND ARRAYS Lecture 04 FUNCTIONS AND ARRAYS 1 Motivations Divide hug tasks to blocks: divide programs up into sets of cooperating functions. Define new functions with function calls and parameter passing. Use functions

More information

Instructor: Eng.Omar Al-Nahal

Instructor: Eng.Omar Al-Nahal Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar

More information

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

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays The University Of Michigan Lecture 07 Andrew M. Morgan Sorting Arrays Element Order Of Arrays Arrays are called "random-access" data structures This is because any element can be accessed at any time Other

More information

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

More on Arrays CS 16: Solving Problems with Computers I Lecture #13 More on Arrays CS 16: Solving Problems with Computers I Lecture #13 Ziad Matni Dept. of Computer Science, UCSB Announcements Homework #12 due today No homework assigned today!! Lab #7 is due on Monday,

More information

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

Chapter 7 Array. Array. C++, How to Program Chapter 7 Array C++, How to Program Deitel & Deitel Spring 2016 CISC 1600 Yanjun Li 1 Array Arrays are data structures containing related data items of same type. An array is a consecutive group of memory

More information

Lecture #8-10 Arrays

Lecture #8-10 Arrays Lecture #8-10 Arrays 1. Array data structure designed to store a fixed-size sequential collection of elements of the same type collection of variables of the same type 2. Array Declarations Creates a Storage

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

CMSC131. Arrays: The Concept

CMSC131. Arrays: The Concept CMSC131 Data Structures: The Array Arrays: The Concept There are a wide variety of data structures that we can use or create to attempt to hold data in useful, organized, efficient ways. The MaritanPolynomial

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

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

Review of Important Topics in CS1600. Functions Arrays C-strings Review of Important Topics in CS1600 Functions Arrays C-strings Array Basics Arrays An array is used to process a collection of data of the same type Examples: A list of names A list of temperatures Why

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

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

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Lesson 06 Arrays MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL Array An array is a group of variables (called elements or components) containing

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Two ways to pass arguments to functions in many programming languages are pass-by-value and pass-by-reference. When an argument is passed by value, a copy of the argument s value is made and passed (on

More information

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

CS162: Introduction to Computer Science II

CS162: Introduction to Computer Science II CS162: Introduction to Computer Science II Java Fundamentals 1 Primitive Types 2 1 Primitive types: Primitive types byte, short, int, long, float, double, char, boolean Example: int size = 42; size is

More information

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

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations CS162: Introduction to Computer Science II Primitive Types Java Fundamentals 1 2 Primitive types The eight primitive types in Java Primitive types: byte, short, int, long, float, double, char, boolean

More information

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

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7 Sorting Algorithms One of the fundamental problems of computer science is ordering a list of items. There s a plethora of solutions to this problem, known as sorting algorithms. Some sorting algorithms

More information

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

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements Admin. CS 112 Introduction to Programming q Puzzle Day from Friday to Monday Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email:

More information

Introduction to Microsoft.NET

Introduction to Microsoft.NET Introduction to Microsoft.NET.NET initiative Introduced by Microsoft (June 2000) Vision for embracing the Internet in software development Independence from specific language or platform Applications developed

More information

Control Statements. Musa M. Ameen Computer Engineering Dept.

Control Statements. Musa M. Ameen Computer Engineering Dept. 2 Control Statements Musa M. Ameen Computer Engineering Dept. 1 OBJECTIVES In this chapter you will learn: To use basic problem-solving techniques. To develop algorithms through the process of topdown,

More information