Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Collections

Size: px
Start display at page:

Download "Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Collections"

Transcription

1 Computer Science 252 Problem Solving with Java The College of Saint Rose Spring 2014 Topic Notes: Collections Our next major topic involves additional common mechanisms for naming collections of items. Motivation for Collections Sometimes we have a lot of very similar data, and we would like to do similar things to each datum. For example, suppose we wanted to extend our Drag2Shirts example to have 4 shirts instead of just 2. See Example: Drag2Shirts We could go through the program and everywhere we see redshirt and blueshirt, add 2 more variables and 2 more segments of code to deal with the new 2 shirts. See Example: Drag4Shirts That was not terribly painful, but a bit tedious and error prone. Now, what if we wanted to create 10, 20, or 100 shirts to be dragged around the canvas. We d want a better way to name the shirts as a group. We could create a recursive data structure to hold our TShirt objects like we did in some recent examples. This is a useful approach in many cases, but we will now consider some other very common ways to manage collections of objects. Java and other programming languages provide a number of mechanisms to help here. We will consider two in Java. First, we will look at a Java class called the ArrayList, and later a lowerlevel construct common to most modern programming language called arrays. Each allows us to use one name for an entire collection of objects. The Java ArrayList Class Those of you who will go on to take data structures will learn about a variety of ways that collections of data can be stored that vary in complexity, flexibility, and efficiency. We will consider just one of those structures here: the ArrayList. ArrayList is a class that implements an abstract data type provided by the standard Java utility library. Let s see how to use them through an example: we will replace the 4 names of TShirt objects in the Drag4Shirts example with a single ArrayList that holds all 4. See Example: Drag4ShirtsArrayList

2 This program has the same functionality, but the 4 variables for the TShirts has been replaced by a single collection, an ArrayList of TShirt objects. We consider each change that was made to the program to see the basic usage of an ArrayList. First, we need to add an import statement to the top of our program. import java.util.arraylist; This allows us to use the class name ArrayList in the rest of the file and Java will know we mean to use the one in the java.util package. Next, we declare an instance variable for our ArrayList: private ArrayList<TShirt> shirts; This looks a little different than any variable declaration we have seen before. Since an ArrayList can be used to hold objects of any type, we need to tell Java what type of objects will be stored in this particular ArrayList. In this case, it s TShirts. So we place that type inside the < and >. This is called a type parameter. Like most Java classes, we need to construct an instance of the class in order use it. This is done in the first statement of the begin method: shirts = new ArrayList<TShirt>(); This is much like other constructions we have seen, but we again need to include the type parameter so Java will give us an ArrayList that is set up to hold a collection of TShirt objects. The TShirt instances are then created, and we need to insert each into the ArrayList. This is done with the add method: shirts.add(shirt); This will take the TShirt named shirt and add it to the first available slot in the ArrayList named shirts. Note that in this case, we are not requesting any specific location within the ArrayList for the shirt. We will later see that we can be more specific here. Note also that we as users of the ArrayList do not know (though when you take data structures, you ll have a pretty good idea) of what s going on inside the ArrayList to add the shirt. We just know that it knows how to do it. When we re done with begin, the ArrayList contains references to 4 TShirt objects. 2

3 In the onmousepress and onmouseexit methods, we need to access the TShirt objects within the ArrayList. We do this with the get method: TShirt shirt = shirts.get(shirtnum); Here, shirtnum is a loop index variable that will range from 0 to one less than the number of items in the ArrayList. We know in this case that there are 4 items, but we can get that information from the ArrayList itself using the size method, as done in the for loops: for (int shirtnum = 0; shirtnum < shirts.size(); shirtnum++) What we see here is that the ArrayList has assigned a number, often called an index, to each TShirt we added to the ArrayList, and we can pass that number to the get method to get back a specific TShirt from the ArrayList. It turns out that the first item we add is given index 0, the next is given index 1, and so on. If we later wanted to get at the first one, we could say: shirts.get(0); but in many cases (like this one), we will access the items within a collection inside a loop, passing in a loop index to the get method. This is our first example of a search operation on a collection we are looking through each object in the collection to find one that contains the Location. More precisely, this is a linear search and we will say more about this later. One of the great things about using a construct like an ArrayList is that we can extend our programs to keep track of a much larger number of objects. If we want to have 10 TShirts on the canvas, we would definitely want to use a collection like an ArrayList to keep track of them. See Example: Drag10Shirts Here, we also place the creation of the TShirts into a loop, but just line them up in a row for simplicity. If we wanted them to be organized into rows or to use a fixed set of colors, we would need to use a more complicated loop in the begin method. (And we will do just that later.) If we wanted to create 20 or 50 or 100 Tshirts, we could do so by changing the loop in the begin method and the remainder of the code does not need to change. ArrayLists in Custom Objects One of the challenges we have seen with constructing custom objects with any level of complexity is that we need to have names for all of the graphical objects we construct. When the object includes large numbers of items, ideally created within a loop, an ArrayList will come in handy to help keep track of them. 3

4 First, we look at a program that doesn t use ArrayLists: See Example: DrawRoads This program draws little segments of roads when we click the mouse. Nothing is new here we could have written this a while ago. But now suppose we want to be able to drag one of these around. We need to have names for all of the components of the road segment so we can do things like move it and check for containment of a point. See Example: DragRoads The enhancements to the WindowController class are all very familiar. It s in the RoadSegment class that we make use of an ArrayList to hold the center stripes of our road segment. Notice the same steps: declare a variable with an ArrayList type that can hold objects of the appropriate type, construct it with new, then add entries with the appropriate types of objects. In the constructor, we do the construction of the ArrayList, then create the actual stripes. In the move method, we loop through the stripes, moving each one. This is nice, but perhaps we want to combine this functionality with that of the program where we could drag around any of 10 shirts. Let s use an ArrayList to keep track of all of the road segments we ve created, so we can drag any segment, not just the most recently drawn one. See Example: DragAllRoads Here, in addition to having an ArrayList to keep track of the components of one of the road segments, we keep an ArrayList of RoadSegment objects in the WindowController class. Removing from an ArrayList We can augment the last example to remove each road segment from the canvas and from the ArrayList. A road segment will be removed if it is being dragged when the mouse leaves the window. See Example: DragAllRoadsRemove The new functionality is in the onmouseexit method of the DragAllRoadsRemove class. If the dragging flag is true when the mouse leaves the window, the currently-dragged segment selectedsegment) should be removed. We first remove it from the canvas, then remove it from the ArrayList. We also set dragging back to false, since the object we were just dragging no longer exists. First, we will look at the removal from the list, which is done with the ArrayList s remove method. We pass as a parameter the element we want to remove, and if it is an element of the list, it is removed. It is important to note that when we remove an element from an ArrayList 4

5 with remove, any subsequent entries will be moved up. That is, if a list contains 5 elements (in positions numbered 0 through 4) and we remove the element at position 2, the ArrayList implementation of remove will shift the element that was in position 3 into position 2, and the one that was in position 4 into position 3. This means we can still use our for loop over the numbers from 0 to size()-1 to visit all of our entries. In other words, remove does not leave a hole at the index from which the element was removed. The new removefromcanvas method is mostly like the ones we have seen in previous examples: to remove the custom object, we remove each of its components. The difference here is that we need to loop through the ArrayList, get and then remove each element. We also should remove the individual FilledRects from the ArrayList, which we do all at once with the clear method. We can also remove elements from an ArrayList by index rather than value. We will see examples of this soon. Other ArrayList methods The examples above demonstrated just a few of the capabilities of the ArrayList class: construction, add, get, size, remove, and clear. The full documentation for the ArrayList can be found at javase/6/docs/api/java/util/arraylist.html Here are a couple of additional methods, some of which will come up in later examples. contains determine if a given object is in the list indexof search for first occurrence of a given object in the list and return its index set replace the contents at an index with a new element A few more examples to bring some of this together: See Example: MovingFlags See Example: PongBricks ArrayLists of Primitive Types Java places a significant restriction on the use of primitive types as the type parameters for generic data structures such as the ArrayList. The following would not be valid Java: ArrayList<int> a = new ArrayList<int>(); The type in the <> must be an object type. Fortunately, Java provides object types that correspond to each primitive type. An Integer object is able to store a single int value, a Double value is able to store a single double value, etc. So the declaration and construction above would need to be: 5

6 ArrayList<Integer> a = new ArrayList<Integer>(); In older versions of Java, programmers would need to be careful to convert back and forth between values of the primitive types and their object encapsulators. To construct an Integer from an int i, one would need to do so explicitly: a.add(new Integer(i)); And to retrieve the int value from an Integer, one would also do so explicitly: a.get(pos).intvalue(); However, recent versions of Java automatically convert between the primitive types and their object encapsulating classes. This is called autoboxing when converting from primitive to boxed encapsulating classes, and autounboxing when going back the other way. However, the effective programmer should always keep in mind that these conversions are occurring, as there is a computational cost to each. Another Example Suppose we have an ArrayList of Integer values, and someone (by a mechanism which is not our concern) has asked us to write a method that will find the largest value in the ArrayList. The following method will achieve this (we assume at least one element in the ArrayList): private static int findmax(arraylist<integer> a) { int max = a.get(0); for (int i=1; i<a.size(); i++) { int val = a.get(i); if (val > max) max = val; return max; The for-each Loop We have seen that a common task with a collection such as an ArrayList is to iterate over its contents. That is, visit every element in the list exactly once to do something to it. It is often the case (and was in many of the examples here) that the specific index of an entry in an ArrayList is not important as we are iterating over its contents. For example, consider the See Example: DragAllRoadsRemove example. It doesn t actually matter the order in which 6

7 we process the items in the ArrayLists in the move and removefromcanvas methods of RoadSegment or in the onmousepress method of DragAllRoadsRemove. In these cases, the counting for loops can be replaced with a related Java construct often called the for-each loop. If we have an ArrayList of objects of some type T and we wish to loop over all entries in the loop, we can replace a counting loop: ArrayList<T> a = new ArrayList<T>();... for (int i = 0; i < a.size(); i++) { T item = a.get(i); // do something with item with a for-each loop: ArrayList<T> a = new ArrayList<T>();... for (T item : a) { // do something with item This construct will loop enough times so that the variable item will be assigned to each entry in a exactly once through the body of the loop. See Example: DragAllRoadsForeach The for-each construct is not always appropriate, however. For example, in the findmax method above, it is more convenient to be able to get the item at position 0 as the initial max and then loop over the entries from positions 1 and up to check for larger values. As you learn more Java, you will see a number of other data structures that can be used with the for-each loop construct. Java Arrays The ArrayList is a Java class, provided as a standard utility with every Java environment. But it is built on top of a more fundamental programming language construct called an array. 7

8 In mathematics, we can refer to large groups of numbers (for example) by attaching subscripts to names. We can talk about numbers n 1, n 2,... An array lets us do the same thing with computer languages. Suppose we wish to have a group of elements all of which have type ThingAMaJig and we wish to call the group things. Then we write the declaration of things as ThingAMaJig[] things; The only difference between this and the declaration of a single item of type ThingAMaJig is the occurrence of [ ] after the type. Like all other objects, a group of elements needs to be created: things = new ThingAMaJig[25]; Again, notice the square brackets. The number in parentheses (25) indicates the number of slots to create, each of which can hold one of the elements. We can now refer to individual elements using subscripts. However, in programming languages we cannot easily set the subscripts in a smaller font placed slightly lower than regular type. As a result we use the ubiquitous [ ] to indicate a subscript. If, as above, we define things to have 25 elements, they may be referred to as: things[0], things[1],..., things[24] We start numbering the subscripts at 0, and hence the last subscript is one smaller than the total number of elements. Thus in the example above the subscripts go from 0 to 24. One warning: When we initialize an array as above, we only create slots for all of the elements, we do not necessarily fill the slots with elements. Actually, the default values of the elements of the array are the same as for instance variables of the same type. If ThingAMaJig is an object type, then the initial values of all elements is null, while if it is int, then the initial values will all be 0. Thus you will want to be careful to put the appropriate values in the array before using them (especially before sending message to them! that s a NullPointerException waiting to happen). In many ways, and array works like an ArrayList, but we will see several differences. Armed with this new construct, let s revisit the shirt dragging program to use arrays. See Example: Drag10ShirtsArray In this code, we we have a single array named shirts. This array is declared as an instance variable, constructed at the start of the begin method, and given values (references to actual TShirts) just after. Then in the onmousepress method, we loop through all of the array entries (as we did previously with an ArrayList) to determine which, if any, has been pressed. Finally, in onmouseexit, we tell all of the shirts to move back to their starting positions. 8

9 Let s see how this differs from the ArrayList version. Our instance variable declaration looks a bit different. When we construct the array in the begin method, we need to tell it how many elements the array will hold (in this case, 10). With the ArrayList, we construct a list and we can add as many things to it as we want. The array can only ever hold the number of elements we provided when we constructed it. When we add items to the array, we need to specify the index explicitly. There is no way to say just add it to the end the way we do with ArrayLists. When we access array elements, we use the bracket notation in much the same way we use the get method of the ArrayList. In this example, we have used an array to keep track of a collection of objects on the canvas. We can also use an array to keep track of the components of a custom object as we did with ArrayLists. An enhancement to this example that shows some of the benefits of arrays, we draw the t-shirts in two rows and use a fixed array of colors for the shirts instead of random colors. See Example: Drag10ShirtsNicer A few things to notice here: We have an array of Colors initialized to 10 pre-defined color names that we ll use for our 10 t-shirts. The construction of the t-shirts takes place in a nested loop to make it easier to organize them into 2 rows of 5 shirts each. Our next enhancement to this example is to draw and drag around 20 shirts, now in 4 rows of 5. See Example: Drag20Shirts Most of the program works correctly just by changing the value of the constant NUM ROWS (hooray for constants!). But...the array of colors is not large enough. We account for this by reusing the colors once we ve run out. This is accomplished with some modulo arithmetic: shirts[shirtnum].setcolor(shirtcolors[shirtnum % shirtcolors.length]); Another Example See Example: DragStudentsS14 9

10 What you ve been waiting for: being the stars of a program. This is another drag objects around example, but this time the objects being dragged are your pictures. In this example, we place the objects randomly on the canvas, but take some care to make sure they do not overlap at all. Notice the helper method overlapsany that helps ensure this. Any image being dragged is also made larger while it s being dragged. Other than that, it s similar to dragging 10 shirts. Arrays of Non-graphical Types There is no reason to limit our usage of arrays to graphical object types. The following is an example of a Java application (rather than an Applet it starts with a main method instead of begin and has no graphics canvas) that uses arrays of String, double, and int. See Example: GradeRangeCounter There are a few items here we haven t used much this semester (the Scanner) but which you have seen before. There are also examples of arrays declared and initialized as final, and an example of an array of int allocated with new. Inserting and Removing with Arrays We have already seen that there is quite a bit to keep track of when using arrays, especially when objects are being added. We need to manage both the size of the array and the number of items it contains. If it fills, we either need to make sure we do not attempt to add another element, or reconstruct the array with a larger size. As a wrapup of our initial discussion of arrays, let s consider two more situations and how we need to deal with them: adding a new item in the middle of an array, and removing an item from the end. For these examples, we will not use graphical objects, just numbers. Arrays can store numbers just as well as they can store references to objects. Suppose we have an array of int large enough to hold 20 numbers. The array would be declared as an instance variable: private int[] a; along with another instance variable indicating the number of ints currently stored in a: private int count; and constructed and initialized: 10

11 a = new int[20]; count = 0; At some point in the program, count contains 10, meaning that elements 0 through 9 of a contain meaningful values. Now, suppose we want to add a new item to the array. So far, we have done something like this: a[count] = 17; count++; This will put a 17 into element 10, and increment the count to 11. But suppose that instead, we want to put the 17 into element 5, and without overwriting any of the data currently in the array. Perhaps the array is maintaining the numbers in order from smallest to largest. In this case, we d first need to move up all of the elements in positions 5 through 9 to instead be in positions 6 through 10, add the 17 to position 5, and then increment count. If the variable insertat contains the position at which we wish to add a new value, and that new value is in the variable val: for (int i=count; i>insertat; i--) { a[i] = a[i-1] a[insertat] = val; count++; Now, suppose we would like to remove a value in the middle. Instead of moving up values to make space, we need to move down the values to fill in the hole that would be left by removing the value. If the variable removeat contains the index of the value to be removed: for (int i=removeat+1; i<count; i++) { a[i-1] = a[i]; count--; The loop is only necessary if we wish to maintain relative order among the remaining items in the array. If that is not important (as is often the case with our graphical objects), we might simply write: a[removeat] = a[count-1]; count--; 11

12 In circumstances where we are likely to insert or remove into the middle of an array during its lifetime, it usually makes sense to take advantage of the higher-level functionality of the ArrayList. Array and ArrayList Summary The following list summarizes the key differences and similarities between arrays and ArrayLists. Declaration To declare an array of elements of some type T: T[] ar; where T can be any type, including primitive types or Object types. And to declare an ArrayList that can hold items of type T: ArrayList<T> al; where T must be an object type. If we want to store a primitive type, we must use Java s corresponding object wrappers (e.g., Integer when we want to store items of type int). Construction To construct (allocate space for) our array of n elements of type T: ar = new T[n]; Once constructed, the array will always have space for n elements of type T if we want a larger or smaller array, we would have to construct a new one. The array constructed will have the default value for the datatype stored in each entry. For object types, all entries begin as null. For primitive number types, they begin as 0. For boolean arrays, they begin as false. To construct an ArrayList: al = new ArrayList<T>(); This ArrayList initially does not contain any values. Its size will be determined by the number of elements we add to it. Adding an Element To add an element to an array, we have to specify the position at which we wish to add the new element: ar[i] = t; 12

13 This will place the item t at position i into our array. i must be in the range 0 to n-1 if we constructed our array to have n entries. If there was already some data stored in position i, it will be overwritten with t. If we want to add the item to the end of the array, that is, the first unoccupied slot in the array, we will need an additional variable to keep track of the number of currently-occupied slots. If this is called asize, and we have been careful to make sure the asize elements in the array occupy slots 0 through asize-1, we can add the element with: ar[asize] = t; asize++; With an ArrayList, the add method takes care of this: al.add(t); Retrieving an Element To get an item from an array, we use the same notation. To put the value from position i in the array into some variable t: t = ar[i]; Whereas with the ArrayList, we need to call a method: t = al.get(i); Visiting All Elements To loop over all elements in the array: for (int i=0; i<asize; i++) { t = ar[i]; // do something with t and an ArrayList; for (int i=0; i<al.size(); i++) { t = al.get(i); // do something with t In both cases, we can also use the for-each loop. 13

14 Two-Dimensional Arrays We can create arrays to hold objects of any type, either basic data types like int and double, or instances of objects such as Image and FilledOval or TShirt. Nothing stops us from defining arrays of arrays. To declare an array, each of whose elements is an array of int: int[][] twodarray; While it is normally written without parentheses, we can think of the above declaration as defining twodarray as having type (int []) []. Thus each element of twodarray is an array of ints. Despite the fact that Java will treat this as an array of arrays, we usually think about this as a twodimensional array, with the elements arranged in a two-dimensional table so that twodarray[i][j] can be seen as the element in theith row andjth column. For example here is the layout for a twodimensional array a with 6 rows (numbered 0 to 5) and 4 columns: a[0][0] a[0][1] a[0][2] a[0][3] 1 a[1][0] a[1][1] a[1][2] a[1][3] 2 a[2][0] a[2][1] a[2][2] a[2][3] 3 a[3][0] a[3][1] a[3][2] a[3][3] 4 a[4][0] a[4][1] a[4][2] a[4][3] 5 a[5][0] a[5][1] a[5][2] a[5][3] Viewed in this way, our two-dimensional array is a grid, much like a map or a spreadsheet. This is a natural way to store things like tables of data or matrices. We access elements of two-dimensional arrays in a manner similar to that used for one dimensional arrays, except that we must provide both the row and column to access an element, giving the row number first. We create a two-dimensional array by providing the number of rows and columns. Thus we can create the two-dimensional array above by writing: int[][] a = new int[6][4]; (Though as good programmers, you would define constants for the number of rows and the number of columns.) A nested for loop is the most common way to access or update the elements of a two-dimensional array. One loop walks through the rows and the other walks through the columns. For example, if we wanted to assign a unique number to each cell of our two-dimensional array, we could do the following: 14

15 for (int row = 0; row < 6; row++) { for (int col = 0; col < 4; col++) { a[row][col] = 4*row + col + 1; This assigns the numbers 1 through 24 to the elements of array a. The array is filled by assigning values to the elements in the first row, then the second row, etc. and results in: And if we wanted to print the above, we can write a loop: for (int row = 0; row < 6; row++) { for (int col = 0; col < 4; col++) { System.out.print(a[row][col] + " "); System.out.println(); You could modify the above to be slightly more interesting by computing a multiplication table. We could just as well process all the elements of column 0 first, then all of column 1, etc., by swapping the order of our loops: for (int col = 0; col < 4; col++) for (int row = 0; row < 6; row++)... For the most part, it doesn t matter which order you choose, though for large arrays it is generally a good idea to traverse the array in the same order that your programming language will store the values in memory. For Java (and C, C++), the data is stored by rows, known as row major order. However, an two-dimensional array in FORTRAN is stored in column major order. You will almost certainly see this again if you go on and take courses like Computer Organization or Operating Systems. Let s look at an example that makes use of a small (3 3) two-dimensional array: a tic-tac-toe game. 15

16 See Example: TicTacToe Most of the program is pretty straightforward, so we ll focus on the use of the two-dimensional arrays and discuss some of the private helper methods that make the code simpler, especially when checking for winning boards. The array that represents the board is a two-dimensional array of int called marks. Each entry will contain one of three values that will indicate if the cell is empty (0), contains an X (1) or contains an O (2). Named constants make the code involving these numbers easier to understand. Several private helper methods are provided to draw the board and the X s and O s. Look a bit at the onmousepress method, where the game is played. When the mouse is pressed and it is determined which (if any) of the 9 spaces contain the press point, we check to see if the space is occupied. If not, the array entry is set and the appropriate mark is drawn on the screen. From there, the checkgamewon method is called to see if this last move led to a win. If not, we call the checkallfilled method to see if all squares are now occupied, meaning the game ends in a tie. A hopefully more interesting use of two-dimensional arrays is to manage the bricks in a breakout game. See Example: Breakout This is a greatly-enhanced version of our last pong game, where there are now a series of bricks that get removed as the ball bounces off one of them. The most relevant to the current discussion is the two-dimensional array in the BrickCollection class. For the game as written, the bricks could be stored in a one-dimensional array or even an ArrayList. However, by storing them in a two-dimensional array, we can have the additional information about the positions if we wanted to enhance the game to have different point values based on position, for example. Two-Dimensional Matrices A very common use of two-dimensional arrays is the representation of matrices. We will look at an example of a class that represents two-dimensional square matrices and provides some basic operations on them. See Example: Matrix2D The class is capable of holding a square matrix of double values of any positive dimension. Comments within the example explain much of what is happening. Note in particular the use of the two-dimensional array as an instance variable which stores the matrix entries, the use of exceptions to handle error conditions, and the main method that tests out the methods of the class. 16

Computer Science 210 Data Structures Siena College Fall 2018

Computer Science 210 Data Structures Siena College Fall 2018 Computer Science 210 Data Structures Siena College Fall 2018 Topic Notes: The ArrayList Arrays are a very common method to store a collection of similar items. Arrays work very well for a lot of situations,

More information

Topic Notes: Java and Objectdraw Basics

Topic Notes: Java and Objectdraw Basics Computer Science 120 Introduction to Programming Siena College Spring 2011 Topic Notes: Java and Objectdraw Basics Event-Driven Programming in Java A program expresses an algorithm in a form understandable

More information

AP Computer Science Lists The Array type

AP Computer Science Lists The Array type AP Computer Science Lists There are two types of Lists in Java that are commonly used: Arrays and ArrayLists. Both types of list structures allow a user to store ordered collections of data, but there

More information

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output Last revised January 12, 2006 Objectives: 1. To introduce arithmetic operators and expressions 2. To introduce variables

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

CS112 Lecture: Working with Numbers

CS112 Lecture: Working with Numbers CS112 Lecture: Working with Numbers Last revised January 30, 2008 Objectives: 1. To introduce arithmetic operators and expressions 2. To expand on accessor methods 3. To expand on variables, declarations

More information

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7 CPS109 Course Notes 7 Alexander Ferworn Unrelated Facts Worth Remembering The most successful people in any business are usually the most interesting. Don t confuse extensive documentation of a situation

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

11 Data Structures Foundations of Computer Science Cengage Learning

11 Data Structures Foundations of Computer Science Cengage Learning 11 Data Structures 11.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define a data structure. Define an array as a data structure

More information

6.001 Notes: Section 6.1

6.001 Notes: Section 6.1 6.001 Notes: Section 6.1 Slide 6.1.1 When we first starting talking about Scheme expressions, you may recall we said that (almost) every Scheme expression had three components, a syntax (legal ways of

More information

CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15)

CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15) CS201 ArrayLists, Generics, and Dynamic Data Structures (Chapters 14, 15) A data structure is a software construct used to organize our data in a particular way. Some common data structures include lists,

More information

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Up to here Not included in program Java collections framework prebuilt data structures interfaces and methods for manipulating

More information

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Searching and Sorting

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Searching and Sorting Computer Science 5 Problem Solving with Java The College of Saint Rose Spring 016 Topic Notes: Searching and Sorting Searching We all know what searching is looking for something. In a computer program,

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Searching and Sorting

Computer Science 210 Data Structures Siena College Fall Topic Notes: Searching and Sorting Computer Science 10 Data Structures Siena College Fall 016 Topic Notes: Searching and Sorting Searching We all know what searching is looking for something. In a computer program, the search could be:

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

Declaring and ini,alizing 2D arrays

Declaring and ini,alizing 2D arrays Declaring and ini,alizing 2D arrays 4 2D Arrays (Savitch, Chapter 7.5) TOPICS Multidimensional Arrays 2D Array Allocation 2D Array Initialization TicTacToe Game // se2ng up a 2D array final int M=3, N=4;

More information

CS159 Midterm #1 Review

CS159 Midterm #1 Review Name: CS159 Midterm #1 Review 1. Choose the best answer for each of the following multiple choice questions. (a) What is the effect of declaring a class member to be static? It means that the member cannot

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

Static Methods. Why use methods?

Static Methods. Why use methods? Static Methods A method is just a collection of code. They are also called functions or procedures. It provides a way to break a larger program up into smaller, reusable chunks. This also has the benefit

More information

ECE 122 Engineering Problem Solving with Java

ECE 122 Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction Outline Problem: How do I input data and use it in complicated expressions Creating complicated expressions

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures Computer Science 210 Data Structures Siena College Fall 2018 Topic Notes: Linear Structures The structures we ve seen so far, Vectors/ArrayLists and linked list variations, allow insertion and deletion

More information

Creating Two-dimensional Arrays

Creating Two-dimensional Arrays ANY TYPE CAN BE USED as the base type of an array. You can have an array of ints, an array of Strings, an array of Objects, and so on. In particular, since an array type is a first-class Java type, you

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #9 John Ridgway February 26, 2015 1 Recursive Definitions, Algorithms, and Programs Recursion in General In mathematics and computer science

More information

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle

CS211 Computers and Programming Matthew Harris and Alexa Sharp July 9, Boggle Boggle If you are not familiar with the game Boggle, the game is played with 16 dice that have letters on all faces. The dice are randomly deposited into a four-by-four grid so that the players see the

More information

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017

Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017 Due: Wednesday, October 18, 11:59 pm Collaboration Policy: Level 1 Group Policy: Pair-Optional Lab 4: Super Sudoku Solver CSCI 2101 Fall 2017 In this week s lab, you will write a program that can solve

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Complexity and Asymptotic Analysis

Computer Science 210 Data Structures Siena College Fall Topic Notes: Complexity and Asymptotic Analysis Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Complexity and Asymptotic Analysis Consider the abstract data type, the Vector or ArrayList. This structure affords us the opportunity

More information

D - Tic Tac Toe. Let's use our 9 sparkles to build a tic tac toe game! 2017 courses.techcamp.org.uk/ Page 1 of 9

D - Tic Tac Toe. Let's use our 9 sparkles to build a tic tac toe game! 2017 courses.techcamp.org.uk/ Page 1 of 9 D - Tic Tac Toe Let's use our 9 sparkles to build a tic tac toe game! 2017 courses.techcamp.org.uk/ Page 1 of 9 INTRODUCTION Let's use our 9 sparkles to build a tic tac toe game! Step 1 Assemble the Robot

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013 1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it

More information

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING

UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING UNIVERSITY OF CALIFORNIA, SANTA CRUZ BOARD OF STUDIES IN COMPUTER ENGINEERING CMPE13/L: INTRODUCTION TO PROGRAMMING IN C SPRING 2012 Lab 3 Matrix Math Introduction Reading In this lab you will write a

More information

CS 134 Programming Exercise 2:

CS 134 Programming Exercise 2: CS 134 Programming Exercise 2: Dirty Laundry Objective: To gain experience using conditionals. The Scenario. One thing some students have to figure out for the first time when they come to college is how

More information

Learning objec-ves. Declaring and ini-alizing 2D arrays. Prin-ng 2D arrays. Using 2D arrays Decomposi-on of a solu-on into objects and methods

Learning objec-ves. Declaring and ini-alizing 2D arrays. Prin-ng 2D arrays. Using 2D arrays Decomposi-on of a solu-on into objects and methods Learning objec-ves 2D Arrays (Savitch, Chapter 7.5) TOPICS Using 2D arrays Decomposi-on of a solu-on into objects and methods Multidimensional Arrays 2D Array Allocation 2D Array Initialization TicTacToe

More information

Repetition Through Recursion

Repetition Through Recursion Fundamentals of Computer Science I (CS151.02 2007S) Repetition Through Recursion Summary: In many algorithms, you want to do things again and again and again. For example, you might want to do something

More information

Bits, Words, and Integers

Bits, Words, and Integers Computer Science 52 Bits, Words, and Integers Spring Semester, 2017 In this document, we look at how bits are organized into meaningful data. In particular, we will see the details of how integers are

More information

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory Pointers A pointer is simply a reference to a variable/object Compilers automatically generate code to store/retrieve variables from memory It is automatically generating internal pointers We don t have

More information

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information

More information

STUDENT LESSON A12 Iterations

STUDENT LESSON A12 Iterations STUDENT LESSON A12 Iterations Java Curriculum for AP Computer Science, Student Lesson A12 1 STUDENT LESSON A12 Iterations INTRODUCTION: Solving problems on a computer very often requires a repetition of

More information

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller Table of Contents Introduction!... 1 Part 1: Entering Data!... 2 1.a: Typing!... 2 1.b: Editing

More information

Array Based Lists. Collections

Array Based Lists. Collections Array Based Lists Reading: RS Chapter 15 1 Collections Data structures stores elements in a manner that makes it easy for a client to work with the elements Specific collections are specialized for particular

More information

17 Multiple Inheritance and ADT Extensions

17 Multiple Inheritance and ADT Extensions Object-Oriented Design Lecture 17 CS 3500 Spring 2010 (Pucella) Friday, Mar 19, 2010 17 Multiple Inheritance and ADT Extensions We looked last time at inheritance and delegation as two ways to reuse implementation

More information

CS 134 Programming Exercise 3:

CS 134 Programming Exercise 3: CS 134 Programming Exercise 3: Repulsive Behavior Objective: To gain experience implementing classes and methods. Note that you must bring a program design to lab this week! The Scenario. For this lab,

More information

Computer Science 202 Introduction to Programming The College of Saint Rose Fall Topic Notes: Conditional Execution

Computer Science 202 Introduction to Programming The College of Saint Rose Fall Topic Notes: Conditional Execution Computer Science 202 Introduction to Programming The College of Saint Rose Fall 2012 Topic Notes: Conditional Execution All of our programs so far have had one thing in common: they are entirely sequential.

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

Programming for Electrical and Computer Engineers. Pointers and Arrays

Programming for Electrical and Computer Engineers. Pointers and Arrays Programming for Electrical and Computer Engineers Pointers and Arrays Dr. D. J. Jackson Lecture 12-1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements.

More information

CS 3410 Ch 7 Recursion

CS 3410 Ch 7 Recursion CS 3410 Ch 7 Recursion Sections Pages 7.1-7.4, 7.7 93-319, 333-336 7.1 Introduction 1. A recursive method is a method that either directly or indirectly makes a call to itself. [Weiss]. It does this by

More information

An Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables

An Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables Activation Records The storage (for formals, local variables, function results etc.) needed for execution of a subprogram is organized as an activation record. An Activation Record for Simple Subprograms.

More information

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we have to talk about the way in which we represent the

More information

Arrays in Java Multi-dimensional Arrays

Arrays in Java Multi-dimensional Arrays Suppose you are tasked with writing a program to help maintain seating records for a theatre company. The auditorium has 25 rows, each of which contains 30 seats. One utility you need to provide is tracking

More information

Arrays. myints = new int[15];

Arrays. myints = new int[15]; Arrays As you know from COMP 202 (or equivalent), an array is a data structure that holds a set of elements that are of the same type. Each element in the array can be accessed or indexed by a unique number

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved. Chapter 5 Arrays 1 5.1 Creating and Using Arrays A collection of data items stored under a single name is known as a data structure. An object is one kind of data structure, because it can store multiple

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Recursive Methods

Computer Science 210 Data Structures Siena College Fall Topic Notes: Recursive Methods Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Recursive Methods You have seen in this course and in your previous work that iteration is a fundamental building block that we

More information

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved.

Chapter 12: Pointers and Arrays. Chapter 12. Pointers and Arrays. Copyright 2008 W. W. Norton & Company. All rights reserved. Chapter 12 Pointers and Arrays 1 Introduction C allows us to perform arithmetic addition and subtraction on pointers to array elements. This leads to an alternative way of processing arrays in which pointers

More information

Functions, Pointers, and the Basics of C++ Classes

Functions, Pointers, and the Basics of C++ Classes Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists 1 A programming problem Consider the following task: Double values representing grades are read until the user enters a negative

More information

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable CISC-124 20180122 Today we looked at casting, conditionals and loops. Casting Casting is a simple method for converting one type of number to another, when the original type cannot be simply assigned to

More information

You must bring your ID to the exam.

You must bring your ID to the exam. Com S 227 Spring 2017 Topics and review problems for Exam 2 Monday, April 3, 6:45 pm Locations, by last name: (same locations as Exam 1) A-E Coover 2245 F-M Hoover 2055 N-S Physics 0005 T-Z Hoover 1213

More information

Lecture Notes on Memory Layout

Lecture Notes on Memory Layout Lecture Notes on Memory Layout 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 11 1 Introduction In order to understand how programs work, we can consider the functions,

More information

Two Dimensional Arrays

Two Dimensional Arrays + Two Dimensional Arrays + Two Dimensional Arrays So far we have studied how to store linear collections of data using a single dimensional array. However, the data associated with certain systems (a digital

More information

Module 6: Array in C

Module 6: Array in C 1 Table of Content 1. Introduction 2. Basics of array 3. Types of Array 4. Declaring Arrays 5. Initializing an array 6. Processing an array 7. Summary Learning objectives 1. To understand the concept of

More information

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming Arrays: Higher Dimensional Arrays CS0007: Introduction to Computer Programming Review If the == operator has two array variable operands, what is being compared? The reference variables held in the variables.

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Functions that return lists

Functions that return lists 342 Chapter 23 Functions that return lists If you did exercises 22.5.15 or 22.5.16, you ve already written some functions that return lists, but only in a very simple way: adding one new element to the

More information

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics Inf1-OP Inf1-OP Exam Review Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 20, 2017 Overview Overview of examinable material: Lectures Week 1

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

array Indexed same type

array Indexed same type ARRAYS Spring 2019 ARRAY BASICS An array is an indexed collection of data elements of the same type Indexed means that the elements are numbered (starting at 0) The restriction of the same type is important,

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

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. Lesson 2 VARIABLES Aim Understanding how computer programs store values, and how they are accessed and used in computer programs. WHAT ARE VARIABLES? When you input data (i.e. information) into a computer

More information

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class For this assignment we will be developing a text-based Tic Tac Toe game 1. The key to this assignment is that we re going

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees Computer Science 0 Data Structures Siena College Fall 08 Topic Notes: Trees We ve spent a lot of time looking at a variety of structures where there is a natural linear ordering of the elements in arrays,

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

Garbage Collection (1)

Garbage Collection (1) Coming up: Today: Finish unit 6 (garbage collection) start ArrayList and other library objects Wednesday: Complete ArrayList, basics of error handling Friday complete error handling Next week: Recursion

More information

Programming Assignment: recursion, recursion, recursion Due date: Thursday, July 26 at 11:29 am

Programming Assignment: recursion, recursion, recursion Due date: Thursday, July 26 at 11:29 am Programming Assignment: recursion, recursion, recursion Due date: Thursday, July 26 at 11:29 am For this project, you will implement several of static methods in a class called Recursive. You will be provided

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

CSC-140 Assignment 5

CSC-140 Assignment 5 CSC-140 Assignment 5 Please do not Google a solution to these problems, cause that won t teach you anything about programming - the only way to get good at it, and understand it, is to do it! 1 Introduction

More information

Curriculum Map Grade(s): Subject: AP Computer Science

Curriculum Map Grade(s): Subject: AP Computer Science Curriculum Map Grade(s): 11-12 Subject: AP Computer Science (Semester 1 - Weeks 1-18) Unit / Weeks Content Skills Assessments Standards Lesson 1 - Background Chapter 1 of Textbook (Weeks 1-3) - 1.1 History

More information

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15 Table of Contents 1 INTRODUCTION... 1 2 IF... 1 2.1 BOOLEAN EXPRESSIONS... 3 2.2 BLOCKS... 3 2.3 IF-ELSE... 4 2.4 NESTING... 5 3 SWITCH (SOMETIMES KNOWN AS CASE )... 6 3.1 A BIT ABOUT BREAK... 7 4 CONDITIONAL

More information

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting

Arrays array array length fixed array fixed length array fixed size array Array elements and subscripting Arrays Fortunately, structs are not the only aggregate data type in C++. An array is an aggregate data type that lets us access many variables of the same type through a single identifier. Consider the

More information

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore Lecture - 20 Intermediate code generation Part-4 Run-time environments

More information

Computer Science 210 Data Structures Siena College Fall Topic Notes: Methods

Computer Science 210 Data Structures Siena College Fall Topic Notes: Methods Computer Science 210 Data Structures Siena College Fall 2017 Topic Notes: Methods As programmers, we often find ourselves writing the same or similar code over and over. We learned that we can place code

More information

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington Arrays and Array Lists CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington 1 Motivation Current limitation: We cannot record multiple

More information

Chief Reader Report on Student Responses:

Chief Reader Report on Student Responses: Chief Reader Report on Student Responses: 2017 AP Computer Science A Free-Response Questions Number of Students Scored 60,519 Number of Readers 308 Score Distribution Exam Score N %At Global Mean 3.15

More information

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1) Topics Data Structures and Information Systems Part 1: Data Structures Michele Zito Lecture 3: Arrays (1) Data structure definition: arrays. Java arrays creation access Primitive types and reference types

More information

DEEPIKA KAMBOJ UNIT 2. What is Stack?

DEEPIKA KAMBOJ UNIT 2. What is Stack? What is Stack? UNIT 2 Stack is an important data structure which stores its elements in an ordered manner. You must have seen a pile of plates where one plate is placed on top of another. Now, when you

More information

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych CS125 : Introduction to Computer Science Lecture Notes #38 and #39 Quicksort c 2005, 2003, 2002, 2000 Jason Zych 1 Lectures 38 and 39 : Quicksort Quicksort is the best sorting algorithm known which is

More information

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values 7_april_ranges_.mcd Understanding Ranges, Sequences, and Vectors Introduction New Mathcad users are sometimes confused by the difference between range variables and vectors. This is particularly true considering

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Lecture Notes on Linear Search

Lecture Notes on Linear Search Lecture Notes on Linear Search 15-122: Principles of Imperative Computation Frank Pfenning Lecture 5 January 28, 2014 1 Introduction One of the fundamental and recurring problems in computer science is

More information

Practice Problems for the Final

Practice Problems for the Final ECE-250 Algorithms and Data Structures (Winter 2012) Practice Problems for the Final Disclaimer: Please do keep in mind that this problem set does not reflect the exact topics or the fractions of each

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

2 Sets. 2.1 Notation. last edited January 26, 2016

2 Sets. 2.1 Notation. last edited January 26, 2016 2 Sets Sets show up in virtually every topic in mathematics, and so understanding their basics is a necessity for understanding advanced mathematics. As far as we re concerned, the word set means what

More information

Introduction to Design Patterns

Introduction to Design Patterns Introduction to Design Patterns First, what s a design pattern? a general reusable solution to a commonly occurring problem within a given context in software design It s not a finished design that can

More information

CS Programming I: ArrayList

CS Programming I: ArrayList CS 200 - Programming I: ArrayList Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455 ArrayLists

More information

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Assignment 1: grid. Due November 20, 11:59 PM Introduction CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,

More information

Chapter Goals. Contents LOOPS

Chapter Goals. Contents LOOPS CHAPTER 4 LOOPS Slides by Donald W. Smith TechNeTrain.com Final Draft Oct 30, 2011 Chapter Goals To implement while, for, and do loops To hand-trace the execution of a program To become familiar with common

More information

CS 302: Introduction to Programming in Java. Lecture 12

CS 302: Introduction to Programming in Java. Lecture 12 CS 302: Introduction to Programming in Java Lecture 12 1 Review What is the 3-step processing for using Objects (think Scanner and Random)? Do objects use static methods or non-static (how do you know)?

More information

Java Programming: from the Beginning

Java Programming: from the Beginning CSc 2310: Principle of Programming g( (Java) Spring 2013 Java Programming: from the Beginning Chapter 5 Arrays 1 Copyright 2000 W. W. Norton & Company. All rights reserved. Outline 5.1 Creating and Using

More information