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

Size: px
Start display at page:

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

Transcription

1 What Are Arrays? CSC 0 Object Oriented Programming Arrays An array is a collection variable Holds multiple values instead of a single value An array can hold values of any type Both objects (reference) and primitive values Each object or value must be of the same type The entire collection shares a single name Individual objects (values) are called elements Elements are accessed by means of their position You'll use a subscript or index to specify position Array Variables In C#, (unlike C++/Pascal) array variables are references A little like object variables Array variables refer to a collection of values Arrays An array stores multiple elements of the same type that type can be simple (value) types or objects for arrays of simple types, each element contains one value of the declared type for arrays of reference types (e.g., objects), every element of the array is a reference to an object of the data type of the array Refer to particular element in the array by position number the name of the array followed by the position number (subscript) of the element in square brackets ([]) [ ] is considered as an operator 4 Arrays: Declaration and Instantiation Array: An Array of Simple Values An array can be allocated using the keyword new to specify how many elements the array should hold bool[] flags; // declare flags flags = new bool[20]; // create an array and make flags a ref. // now flags is reference to another array flags = new bool[10]; grades grades[ 0 ] grades[ 1 ] grades[ 2 ] grades[ ] grades[ 4 ] // declare variable grades; create an array; make grades a // reference of the array int[] grades = new int[12]; float[] prices = new float[500]; string[] codes = new string[26]; position number (index or subscript) of the element within array grades grades[ 5 ] grades[ 6 ] grades[ 7 ] grades[ 8] grades[ 9 ] grades[ 10 ] Time1[] times; times = new Time1[10]; grades[ 11 ] A 12-element array of values. 6 1

2 Array: An Array of Objects Summary of Operators times position number (index or subscript) of the element within array times times[ 0 ] times[ 1 ] times[ 2 ] times[ ] times[ 4 ] times[ 5 ] times[ 6 ] times[ 7 ] times[ 8] times[ 9 ] ref to obj 0 ref to obj 1 ref to obj 2 ref to obj ref to obj 4 ref to obj 5 ref to obj 6 ref to obj 7 ref to obj 8 ref to obj 9 Operators Associativity Type () [] left to right highest (unary postfix) ! (type) right to left unary (unary prefix) * / % left to right multiplicative + - left to right additive < <= > >= left to right relational ==!= left to right equality & left to right boolean logical AND ^ left to right boolean logical exclusive OR left to right boolean logical inclusive OR && left to right logical AND left to right logical OR?: right to left conditional = += -= *= /= %= right to left assignment Precedence and associativity of the operators discussed so far. A 10-element array of objects 7 8 Arrays as Objects Array: Length In C#, an array behaves very much like an object declaration and instantiation are like objects declare an array variable create an array using new make a variable a reference of an array parameter passing is similar to objects an array has the Length property Each array has a public property called Length that stores the size of the array once an array is created, it has a fixed size It is referenced using the array name (just like any other object): grades.length Note that Length holds the number of elements, not the largest index 9 10 Array and Bound An index used in an array reference must specify a valid element That is, the index value must be in bounds (0 to N-1), where N is the length For example, if the array yg grades can hold 12 values, it can only be indexed using the numbers 0 to 11 problem for (int index=0; index <= grades.length; index++) scores[index] = index*50 + epsilon; It s common to introduce off-by-one errors when using arrays Array Instantiation and Initialization in One Step: Initializer List An initializer list can be used to instantiate and initialize an array in one step The values are delimited by braces and separated by commas Allocate space for the array number of elements in initializer list determines the size of array Elements in array are initialized with the values in the initializer list The new operator is not used Examples: int[] units = 147, 2, 89, 9, 540; char[] lettergrades = 'A', 'B', 'C', 'D', 'F'; string[] wordlist = cs112, computer", television";

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

4 Passing Arguments by Value and by Reference Passing a value type argument to methods The value of an actual argument is copied to the formal argument The formal argument has its own memory location Any changes to the formal argument in the method do not affect the actual argument Calling a Method Each time a method is called, the actual arguments in the invocation are copied into the formal arguments If a value type, it is the value that is copied If a reference type, it is the reference that is copied Passing a reference type argument to methods A copy of the reference to the object/array is made to the formal argument Any changes to the contents of the object/array in the method, do affect the object/array outside the method Because both the formal argument and the actual argument are reference to the same object/array int num = SquareSum (2, ); static int SquareSum (int num1, int num2) num1 = num1 + num2; num1 return num1 * num1; num Calling a Method: Value Type Calling a Method: Value Type Even if formal arguments and actual arguments have the same name, modifications to formal arguments in a method will not affect actual arguments int n1 = 2; n1 2 int num1 = 2; num1 2 int n2 = ; n2 int num2 = ; num2 int num = SquareSum (n1, n2); int num = SquareSum (num1, num2); static int SquareSum (int num1, int num2) num1 = num1 + num2; num1 return num1 * num1; num2 25 static int SquareSum (int num1, num1 = num1 + num2; return num1 * num1; int num2) num1 25 num Calling a Method: Using ref/out Passing Arrays to Methods If an argument of a method is ref (or out), then the formal argument and the actual argument are aliases of each other, i.e. they share the same memory cell n1 int n1 = 2; n2 int n2 = ; num int num = SquareSum (ref n1, ref n2); static int SquareSum (ref int num1, ref int num2) num1 = num1 + num2; return num1 * num1; What happens when you pass an array variable to a method? [Assume a variable named nums is original array] 2 4

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

6 Calling a Method: Side Effect of Reference Calling a Method: Side Effect If an argument is a reference type, then modifying the content/state of the array/object through the reference will have side effect Each time a method is called, the actual arguments in the invocation are copied into the formal arguments If a value type, then it is the value that is copied If a reference type, then it is the reference that is copied The formal argument and the actual argument are different variables, with different memory locations. int[] array = 1, 2, ; DoubleArray (array); array static void DoubleArray (int[] array) array for (int i = 0; i < array.length; i++) i array[i] *= 2; 12 6 int[] array = 1, 2, ; DoubleArray( array ); array static void DoubleArray (int[] array) array for (int i = 0; i < array.length; i++) i array[i] *= 2; array = new int[] 2, 4, 6, 8; Arrays as Parameters: Summary If an argument of a method is an array, a reference to a array is passed to the method Changing an array element in the method changes the original i An array element can be passed to a method as well, and follow the parameter passing rules of that element's type 1 // ArrayReferenceTest.cs 2 // Testing the effects of passing array references // by value and by reference. 4 using System; Declare and initialize 5 using System.Drawing; 6 using System.Collections; integer array firstarray 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; public class ArrayReferenceTest System.Windows.Forms.Form : 12 1 private System.Windows.Forms.Label outputlabel; 14 private System.Windows.Forms.Button showoutputbutton; [STAThread] Declare integer array 17 static void Main() firstarraycopy and have it Application.Run( new ArrayReferenceTest() reference firstarray); private void showoutputbutton_click( object sender, 2 System.EventArgs e ) 25 // create and initialize firstarray 26 int[] firstarray = 1, 2, ; // copy firstarray reference 29 int[] firstarraycopy = firstarray; 0 1 outputlabel.text += 2 "Test passing firstarray reference by value"; 4 outputlabel.text += "\n\ncontents of firstarray " + 5 "before calling FirstDouble:\n\t"; ArrayReferenceTe st.cs 6 7 // print contents of firstarray 8 for ( int i = 0; i < firstarray.length; i++ ) 9 outputlabel.text += firstarray[ i ] + " "; ArrayReferenceTe // pass reference firstarray by value to FirstDouble st.cs 42 FirstDouble( firstarray ); Test whether firstarray and firstarraycopy 4 44 outputlabel.text += "\n\ncontents of firstarray reference the after same " object + 45 "calling FirstDouble\n\t"; Declare integer array secondarraycopy and // print contents of firstarray set it to reference Output secondarray contents of firstarray 48 for ( int i = 0; i < firstarray.length; i++ ) Declare and initialize integer arry 49 outputlabel.text += firstarray[ i ] + " "; secondarray // test whether reference was changed by FirstDouble Call method FirstDouble 52 if ( firstarray == firstarraycopy ) on firstarray 5 outputlabel.text t t += 54 "\n\nthe references refer to the same array\n"; 55 else 56 outputlabel.text += 57 "\n\nthe references refer to different arrays\n"; // create and initialize secondarray Output contents of firstarray 60 int[] secondarray = 1, 2, ; // copy secondarray reference 6 int[] secondarraycopy = secondarray; outputlabel.text += "\ntest passing secondarray " + 66 "reference by reference"; outputlabel.text += "\n\ncontents of secondarray " + 69 "before calling SecondDouble:\n\t"; // print contents of secondarray before method call 72 for ( int i = 0; i < secondarray.length; i++ ) 7 outputlabel.text += secondarray[ i ] + " "; 74 Test whether secondarray ArrayReferenceTe 75 SecondDouble( ref secondarray ); 76 and secondarraycopy 77 outputlabel.text += "\n\ncontents st.cs of reference secondarray the same " + object SecondDouble:\n\t"; 78 "after calling // print contents of secondarray after method call Replace each element in the array for ( int i = 0; i < secondarray.length; i++ ) outputlabel.text += secondarray[ i ] + " "; Output by twice contents its value of secondarray 8 84 // test whether reference was changed by SecondDouble Set array to reference a new 85 if ( secondarray == secondarraycopy ) integer array containing the 86 outputlabel.text += values Call method 11, 12 and SecondDouble "\n\nthe references refer to the same array\n"; else and pass secondarray by 89 outputlabel.text += reference 90 "\n\nthe references refer to different arrays\n"; // end method showoutputbutton_click Output contents of secondarray 9 94 // modify elements of array and attempt to modify 95 // reference 96 void FirstDouble( int[] array ) // 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 10 array = new int[] 11, 12, 1 ;

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

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

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

10 Other ArrayList Methods ArrayLists can make your code simpler Don't have to explicitly size them Many methods that eliminate "hand-coding" Contains() performs a linear search on the list IndexOf() to retrieve the position of an item (linear) Sort() to order the items (if they are sortable) BinarySearch() to locate a value in a sorted list These last three work on arrays as well Use the methods in the System.Array class 55 Sorting Arrays Sorting data is important in many applications Bubble Sort array of size n Make n passes through the array For each pass, compare every pair of successful elements If the first is larger then the second, swap the elements Easy to program Runs slowly.net Framework includes high-speed sorting capabilities 56 BubbleSorter.cs 1 // BubbleSorter.cs 2 // Sorting an array's values into ascending order. using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class BubbleSorter : System.Windows.Forms.Form private System.Windows.Forms.Button sortbutton; 1 private System.Windows.Forms.Label outputlabel; // Visual Studio.NET generated code Declare and initialize array a [STAThread] 18 static ti void Main() Output the contents of array a Application.Run( new BubbleSorter() ); 21 Call method Bubble sort on array a 22 2 private void sortbutton_click( object sender, System.EventArgs e ) int[] a = 2, 6, 4, 8, 10, 12, 89, 68, 45, 7 ; outputlabel.text += "Data items in original order\n"; 29 0 for ( int i = 0; i < a.length; i++ ) 1 outputlabel.text += " " + a[ i ]; 2 sort elements in array a // 4 BubbleSort( a ); 5 6 outputlabel.text += "\n\ndata items in ascending order\n"; 7 8 for ( int i = 0; i < a.length; i++ ) 9 outputlabel.text += " " + a[ i ]; Swaps two elements 40 BubbleSorter.cs of an array 41 // end method sortbutton_click If an given element is 42 bigger then the Output following sorted array a 4 // sort the elements of an array with bubble sort element, swap the elements 44 public void BubbleSort( int[] b ) 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 Perform b.length-1 Perform passes contents of for loop // swap two elements of an array for each element of array b 55 public void Swap( int[] c, int first ) int hold; // temporary holding area for swap hold = c[ ]; first 60 c[ first ] = c[ first + 1 ]; 61 c[ first + 1 ] = hold; 62 6 Searching Arrays: Linear Search and Binary Search 59 Searching an Array with Linear Search 60 Arrays may be very large Sometimes necessary to determine if a particular element is in the array Linear Search Binary Search Return index of search key in array Begin search at the beginning of array, continue sequentially On average, half the array needs to be searched to find desired element Works well for small or unsorted arrays 10

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

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

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

An array can hold values of any type. The entire collection shares a single name 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)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

CS 112 Introduction to Programming

CS 112 Introduction to Programming CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin. q Puzzle Day

More information

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

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto CS 170 Java Programming 1 Working with Rows and Columns Slide 1 CS 170 Java Programming 1 Duration: 00:00:39 Create a multidimensional array with multiple brackets int[ ] d1 = new int[5]; int[ ][ ] d2;

More information

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

Objectivities. Experiment 1. Lab6 Array I. Description of the Problem. Problem-Solving Tips Lab6 Array I Objectivities 1. Using rand to generate random numbers and using srand to seed the random-number generator. 2. Declaring, initializing and referencing arrays. 3. The follow-up questions and

More information

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

Visual Studio.NET.NET Framework. Web Services Web Forms Windows Forms. Data and XML classes. Framework Base Classes. Common Language Runtime Intro C# Intro C# 1 Microsoft's.NET platform and Framework.NET Enterprise Servers Visual Studio.NET.NET Framework.NET Building Block Services Operating system on servers, desktop, and devices Web Services

More information

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

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold Arrays 1. Introduction An array is a consecutive group of memory locations that all have the same name and the same type. A specific element in an array is accessed by an index. The lowest address corresponds

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

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

Array. Prepared By - Rifat Shahriyar

Array. Prepared By - Rifat Shahriyar Java More Details Array 2 Arrays A group of variables containing values that all have the same type Arrays are fixed length entities In Java, arrays are objects, so they are considered reference types

More information