Sally Bellacqua and Mary Dring Johnson Thomas Jefferson High School for Science and Technology, Alexandria, Virginia

Size: px
Start display at page:

Download "Sally Bellacqua and Mary Dring Johnson Thomas Jefferson High School for Science and Technology, Alexandria, Virginia"

Transcription

1 Be Prepared for the AP * * AP and Advanced Placement are registered trademarks of the College Entrance Examination Board, which does not endorse this book. Computer Science Exam Maria Litvin Phillips Academy, Andover, Massachusetts Practice exam contributors: H. Donald Allen and Craig Morgan Steele Troy High School, Fullerton, California Sally Bellacqua and Mary Dring Johnson Thomas Jefferson High School for Science and Technology, Alexandria, Virginia Skylight Publishing Andover, Massachusetts

2 Copyright 2000 by Maria Litvin and Skylight Publishing This material and the source files are provided to you as a supplement to the Be Prepared for the Computer Science Exam book. You are not authorized to publish or distribute them in any form without our permission. However, you may print out one copy of this chapter and files for personal use and for face-to-face teaching for each copy of the Be Prepared book that you own or receive from your school. Library of Congress Catalog Card Number: ISBN Skylight Publishing 9 Bartlet Street, Suite 70 Andover, MA web: sales@skylit.com support@skylit.com ML Printed in the United States of America

3 Chapter 6. Case Study 6.1. Introduction The RandGen Class Part 1: One Fish in One Dimension Part 2: Many Fishes in Two Dimensions utils Position Neighborhood Fish and Environment Simulation and Display main Appendix: Doing It From Scratch? CS-1

4 CS-2 Chapter 6. Case Study 6.1. Introduction The Case Study is a component of AP CS exams that is based on a complete small software project. You have to get familiar with the case study s features and code and be ready to answer multiple-choice and free-response questions based on these features and their implementation. The case study includes several C++ classes and small client programs that use these classes. The Exam Development Committee provides a description of the case study, its complete code, and some sample questions and exercises long before the exam. The same case study is used for several years. You will receive a copy of the case study code at the exam, but there is not enough time to read it on the spot students are expected to know it quite well beforehand, and it is provided at the exam only for reference. The case study for May 2001 will be Marine Biology by Mike Clancy, Owen Astrachan, and Cary Matsuoka. Its full description in PDF format and complete code are available at The College Board's AP * CS web site: This case study involves simulating the random movement of particles ( fish in a tank ), but the emphasis is more on software development methodology rather than on a realistic marine biology application. As the authors point out a couple of times, tongue in cheek, we will verify this later with the biologists. The case study stays within the C++ subset as defined in the AP CS program. In order to understand the code, you must be familiar with C++ classes, constructors with initializer lists, and overloaded operators. At the same time, the case study hints at object-oriented programming (OOP), modularity, reusability of code topics that you have perhaps avoided so far. At the practical level, you have to know how to handle projects with multiple header files and source modules. Chapter 14 in C++ for You++, Modularity, offers an introduction to that: Elsewhere on our website you can find instructions on how to set up projects with different compilers: The Marine Biology case study consists of two parts. Part 1 is a warm-up mini-project that introduces the RandGen class and uses it to simulate random movement of a single particle ( fish ) in one dimension. The case study doesn t go into the implementation of the RandGen class, but just describes and uses its public functions. The code then defines * AP and Advanced Placement are registered trademarks of the College Entrance Examination Board which does not endorse this book.

5 Chapter 6. Case Study CS-3 one class, AquaFish, which represents one fish in a narrow (one-dimensional) aquarium tank. Part 2 extends the application into a rectangular area in two dimensions and handles multiple fishes. This part gets quite complex, with six interacting classes and an additional utils.cpp module. After looking at the case study code one may wonder why so much code is necessary to accomplish a fairly straightforward simulation. This is a good question and we briefly address it in an Appendix (Section 6.5). In any case, the case study is probably not too far from how things are sometimes done in the real world. One of the goals of Part 2 is to introduce students to the realistic task of reading, understanding, and modifying someone else s rather convoluted code. (According to the case study narrative, the code presumably had been written several years earlier by biology research students.) The authors were also constrained by the C++ subset, which excludes such C++ features as friends and inheritance. The latter allows a programmer to define hierarchies of related objects, which is the defining feature of OOP The RandGen Class The RandGen class provides functions that return random numbers. More precisely, these numbers are called pseudorandom because they are generated according to some algorithm, as opposed to falling randomly from heaven. But they are distributed fairly uniformly and meet some other statistical criteria for randomness. If you peek inside randgen.cpp (which you are neither required nor supposed to do), you will see that it uses the srand function to seed the random number generator and the rand function to generate random integers. These functions from the standard C/C++ library have been familiar to programmers for many years and are standard in ANSI C, Windows, and Unix. A seed is used to initialize a sequence of random numbers; different seeds result in different sequences. The RandGen class provides an interface with two constructors and two (overloaded) RandInt member functions: RandGen randomvals; RandGen randomvals(int s); // Creates a random number generator // (or, as we say in OOP, // "random number generator object") // with un unpredictable seed // Creates a random number generator with // the given seed s int randomvals.randint(int n); // Returns a random integer x: 0 <= x <= n-1 int randomvals.randint(int m, int n); // Returns a random integer x: m <= x <= n It also has two RandReal member functions, which are not used in the case study code but can potentially come up in questions. Note the following properties of RandGen:

6 CS-4 Chapter 6. Case Study 1. The default constructor (i. e., the constructor with no arguments) seeds the random number generator with a different seed each time the program is executed. This results in a different sequence of random numbers each time you run your program. 2. Another constructor, with one argument, allows you to seed the random number generator with a specified seed. If you use the same seed each time you run your program, then it generates the same sequence of random numbers on each run a feature useful for debugging. (This is sort of the opposite of what you might be used to with the rand function. In order to generate different sequences of random numbers with rand you have to seed the random number generator with some random seed yourself, using the srand function. The computer s system time is customarily used for that purpose. For example: srand(unsigned(time(0))); // Seed the random number generator // based on the current system time In fact, that s exactly what RandGen s default constructor does.) 3. Once you have initialized the first RandGen object (i.e., the first instance of the RandGen class) anywhere in your program, either with the default constructor or with a specified seed, all other instances of RandGen will skip initialization and draw random numbers from the same sequence. This means you cannot obtain two different sequences generated with different seeds inside the same run of the program. For example: RandGen r1(2001); // Defines the first RandGen object // seeded with 2001 RandGen r2(2002); // Defines a second RandGen object, but the // seed parameter, 2002, is ignored -- it will // draw random numbers from the same sequence // as r1 (This is understandable since RandGen is based on srand and rand, and these functions support only one seeded sequence of random numbers at a time. You may wonder how r2 knows that r1 exists. It turns out that the RandGen class has a static data member, ourinitialized, which is shared by all instances of the class. ourinitialized is initially set to 0; once the first instance of the class is initialized, ourinitialized is set to 1 and all other instances skip the call to srand. Static class members are not in the AP subset.) 4. RandInt is similar to the random(n) function defined in Borland compilers: it returns a random integer from 0 to n-1 (n is not included). For example, randomvals.randint(2) returns 0 or 1 with equal probabilities. RandInt(k,n) on the other hand, returns random numbers from k to n including both ends, k and n.

7 Chapter 6. Case Study CS-5 5. randvals.randreal() returns a random real (double) number 0 x < 1. Actually, the smallest possible distance between these random reals is 1/RAND_MAX. randvals.randreal(a,b) returns a random real number a x < b. The RandReal functions are not really used in the case study code, except inside the RandGen class itself. 53 Consider the following program: int main() RandGen r1(0); RandGen r2(0); int i, sum = 0; for (i = 0; i < 100; i++) sum += r1.randint(1, 3) - r2.randint(1, 3); cout << sum/100. << endl; return 0; Which of the following best describes the outputs when this program is executed a few times? (A) The output is always 0. (B) The output is always 1. (C) The output is always 2. (D) The output is always the same number in the range from -0.3 and 0.3 (but not necessarily 0). (E) The output each time is a different number in the range from -0.3 to 0.3.

8 CS-6 Chapter 6. Case Study Even though r1 and r2 are both seeded with 0, only the first initialization actually takes place (as explained above). The statement sum += r1.randint(1, 3) - r2.randint(1, 3); draws two consecutive random numbers from the same sequence. This sequence is the same for all runs of the program because the random number generator is seeded with 0 when r1 is defined. This eliminates E. The numbers returned by RandInt(1,3) range from 1 to 3, inclusive. Therefore, sum may be incremented by as much as 2 or decremented by as much as 2 on each iteration, whatever the difference might be; sum may also remain the same if that difference is 0. We cannot be sure that the program always prints 0, but, if our random number generator is any good, we cannot accumulate a very large sum. (According to rules of statistics, it is rather unlikely that sum will go beyond two times the standard deviation, which is here approximately equal to So the output will be somewhere between -0.3 and 0.3). The answer is D Part 1: One Fish in One Dimension Part 1 of the case study is a warm-up exercise on how to use the RandGen class in a random walk simulation. Random walk refers to a simulation where a particle jumps repeatedly from its current position to one of the neighboring positions, chosen randomly among all its neighbors. You can ask a number of questions about random walk, such as: How far from the origin, on average, will the particle end up after n steps? How many times will the particle hit the origin in n steps? What is the probability that the particle will ever reach a certain point within n steps? and so on. In Part 1 of the case study, a particle (a fish ) moves between discrete points in one dimension. There are two directions, left and right, and they are chosen with equal probabilities. The fish moves on a segment of a certain length (a tank ) and we count the number of times the fish bumps into the left and right walls of the tank. The case study uses the AquaFish class to represent one fish in a tank, to simulate its random-walk movement, and to count the number of bumps. In the chosen implementation, a fish (i.e., an AquaFish object) is pretty smart: not only does it store information about the tank s size, it also remembers its own position and the current count of bumps and even knows whether to generate a debugging printout:

9 Chapter 6. Case Study CS-7 class AquaFish public: AquaFish(int tanksize); void Swim(); int BumpCount() const; // Swim one foot. // Return the bump count. private: int myposition; int mybumpcount; int mytanksize; bool mydebugging; ; The tank size is passed to the AquaFish constructor and the bump count is returned by the accessor member function BumpCount. The Swim member function implements one step in a random walk. The constructor uses an initializer list to set the tank size and the initial position in the middle of the tank. It also zeroes out the bump count and enables debugging printouts: AquaFish::AquaFish(int tanksize) : myposition(tanksize/2), mytanksize(tanksize), mybumpcount(0), mydebugging(true)

10 CS-8 Chapter 6. Case Study The core of the simulation is implemented in the Swim function: void AquaFish::Swim() RandGen randomvals; int flip; if (myposition == mytanksize - 1) myposition--; else if (myposition == 0) myposition++; else flip = randomvals.randint(2); if (flip == 0) myposition++; else myposition--; if (mydebugging) cout << "*** Position = " << myposition << endl; if (myposition == 0 myposition == mytanksize - 1) mybumpcount++; Or, in a slightly shorter version (without the redundant braces and the debugging printout): void AquaFish::Swim() RandGen randomvals; if (myposition == 0) myposition++; else if (myposition == mytanksize - 1) myposition--; else if (randomvals.randint(2) == 0) myposition++; else myposition--; if (myposition == 0 myposition == mytanksize - 1) mybumpcount++;

11 Chapter 6. Case Study CS-9 The Swim function keeps the fish within the tank. The case study briefly discusses the merits of placing mydebugging inside the AquaFish class. (It would be better as a static member, but this is not in the subset. Otherwise, it just could be a global constant.) Note one peculiarity of AquaFish s implementation: randomvals is constructed locally inside Swim, presumably each time it is called. This is misleading. Actually, the random number generator will be initialized only once: when randomvals is constructed for the first time in the first call to Swim. So the AquaFish class is dependent on this rather unusual property of the RandGen class. A different design would have randomvals constructed outside Swim: it could be a static member of AquaFish or, perhaps, AquaFish could be derived (inherited) from RandGen (but neither option is in the AP subset). Part 1 also provides a test program aquamain.cpp that runs simulations. 54 Suppose we enter 5 for the tank size and 36 for the number of steps in an aquamain run. What will be the expected average bump count after several such runs? (A) 6 (B) 9 (C) 12 (D) 18 (E) 144 Strictly speaking, this is math. But it isn t very deep, and it helps to have some idea what to expect in a given simulation when we test our program. The fish starts out in position 2. After one step it goes to either 1 or 3. After another step it can either reach 0 or 4 (with a bump) or return to 2 with no bump. Of all four possible two-step sequences (right-right, left-left, left-right and right-left), two result in a bump. If the fish is in position 0, then after one step it goes to 1 and after another step it either goes back to 0 (with a bump) or goes to 2. A similar path applies to position 4. As we can see, it makes sense to follow fish movements in pairs of steps. You can sketch a diagram of all possible pairs of steps from all even positions. No matter whether the current position of the fish is 2, 0, or 4, after a pair of steps it has a 50 percent chance of gaining one bump. In 36 steps there are 18 pairs and, on average, half of them will result in bumps. The answer is B.

12 CS-10 Chapter 6. Case Study 6.4. Part 2: Many Fishes in Two Dimensions Part 2 of the case study simulates the movements of several fishes in a rectangular area, represented by a two-dimensional array. The fishes cannot collide, that is each element of the array may hold at most one fish. The movements of the fishes are synchronized so that in each step of the simulation each fish moves into one of the vacant neighboring cells (if any). If all neighboring cells are occupied, the fish stays in its current position. Because they cannot collide, the order in which the fishes are processed is important. In this simulation the fishes are processed left to right along each row starting from the top row and going down: for (r = 0; r < NumRows(); r++) for (c = 0; c < NumCols(); c++)... This simple model is represented in a rather elaborate set of classes. Each class is packaged in its own pair of.h and.cpp files. (This is not a C++ requirement, but it is a common practice.) The classes are said to represent objects: an environment object, a display object, a fish object. As the case study booklet explains, all the class names are nouns; the naming reflects their roles as types of objects. This is a step toward OOP, but only the first step. A true OOP application usually implements a hierarchy of objects, using inheritance (not in the AP subset). The design decisions in OOP allow a lot of freedom in defining objects, their relations, and functions. The central concept is that each object sort of knows how to handle itself. In the case study, for example, the Move function is placed within the Fish class, so a fish knows how to swim. The code for Part 2 comprises nine modules (Table 1). The authors offer a top-down approach to analyzing the fishsim application: first look at the main program; then take the executable program and experiment with it by running it with different data; then examine the higher-level classes, Environment, Fish, Simulation, then proceed to the lower level classes, Display, Neighborhood, Position. The experimentation part may be fun, but it is also time-consuming. We can save a lot of time by going to the source code first. Our approach here complements the case study booklet: it is a bottom-up approach: first we want to look at the lowest-level functions and classes, starting with utils.h and utils.cpp, then proceed to position.h and position.cpp, and so on.

13 Chapter 6. Case Study CS-11 Files Class Functionality fishsim.cpp environ.h environ.cpp fish.h fish.cpp simulate.h simulate.cpp display.h display.cpp nbrhood.h nbrhood.cpp position.h position.cpp utils.h utils.cpp randgen.h randgen.cpp Environment Fish Simulation Display Neighborhood Position RandGen Main program Represents a 2-D grid Represents one fish in the environment Runs one or several steps in the simulation Displays the environment Represents a list of positions Represents a position on a 2-D grid Contains IntToString, Sort, and DebugPrint functions Implements pseudorandom numbers Table 1. The case study files utils utils.cpp contains three free-standing functions (i.e., functions that are not members of any class) that didn t quite fit anywhere else. utils.h contains their prototypes. The first function, apstring IntToString(int n); converts an integer into an apstring. It first builds a string in reverse order: starts at the rightmost digit and proceeds to the left. The characters are appended to the string one by one, which may be quite inefficient: the string has to be expanded, reallocated, and copied several times. The code then unreverses the string, by appending characters one by one to the final result. Normally such a function wouldn t be written from scratch: some library functions or classes would be used. A shorter solution, for example, may rely on the ostrstring class:...

14 CS-12 Chapter 6. Case Study #include <strstream.h> apstring IntToString(int n) char ascii[100]; ostrstream os(ascii, 100); os << n << ends; return apstring(ascii); // The output goes into this array // Ends appends the terminating // null character But standard arrays and ostrstring are not in the AP subset. The second function, Sort, implements Selection Sort (see Be Prepared, p. 76) on an array of Fish, according to their positions. It turns out that this function is never called perhaps it is reserved for future exam questions! The third function, DebugPrint, generates debugging outputs with different indentation and different levels of detail depending on the value of the global variable int LEVEL_OF_DEBUG_DETAIL = 0; defined in the same file. The case study advocates leaving debugging printouts in your code. This helps in testing the program but if you are not careful, it may significantly slow down the final executable because the program will generate debugging strings whether it prints them or not. For example, Fish::Move has a call DebugPrint(1, "Fish " + oldpos.tostring() + " moves to " + mypos.tostring()); This call concatenates strings and actually calls IntToString multiple times before anything moves. A better approach, perhaps, would be to use conditional compilation that excludes all debugging code from the final executable. For instance: #ifdef DEBUG_LEVEL if (DEBUG_LEVEL >= 1) cout << " **** Move::Fish: Fish" << oldpos.tostring() << " moves to " << mypos.tostring() << endl; #endif In any case, never include debugging statements in your AP exam solutions unless specifically instructed to do so. Normally a low-level module like utils would be reusable: that is, potentially useful in all kinds of projects. This one isn t simply because the Sort function depends on the Fish class. Bringing utils into another project would drag with it fish, environ, and all the other modules. It would be easy to convert Sort into a templated function that works with any data type (See Be Prepared, p. 54). You can try it as an exercise. Note that you will have to move the templated version of Sort into utils.h and you will have to add an overloaded < operator for the Fish class.

15 Chapter 6. Case Study CS Position Position is an encapsulated class that represents a position in a two-dimensional grid with integer coordinates myrow and mycol. It provides a default constructor that builds a position with coordinates myrow = -1, mycol = -1, another constructor with two arguments that builds a position with a given row and column, and two accessors, Row() and Col(), that return the respective coordinates. The Position class also offers four functions, North, South, East, and West, that build and return a new position with row or col appropriately incremented or decremented by one. These functions support movements of fishes in four possible directions. Finally, Position has two helper functions, bool Equals and apstring ToString, that are used in the overloaded non-member operators == and << respectively. ToString is also used for generating debugging printouts. The << and == operators could be also implemented without helper functions. For example: ostream & operator << (ostream & out, const Position & pos) out << '(' << pos.row() << ',' << pos.col() << ')'; return out; 55 Assuming that the dimensions of the myworld matrix are greater than 4 and LEVEL_OF_DEBUG_DETAIL is set to 3, what will be the output from the following code? Position p(2,3); p.south(); DebugPrint(3, "Position: " + p.tostring()); (A) No output (B) **** Position: 2 4 (C) **** Position: (2,4) (D) **** Position: (3,3) (E) **** Position: (2,3)

16 CS-14 Chapter 6. Case Study The constructor initializes p s coordinates to myrow = 2, mycol = 3. You might expect the answer D after p.south() presumably increments the row by one. (Note that ToString places myrow and mycol, in this order, inside parentheses and separates them with a comma.) Unfortunately, the South function is used incorrectly in this code. South does not change its object (in fact South is designated const in the class definition); instead, p.south() builds and returns a new position with the row incremented by one, while p remains unchanged. The correct usage to get the answer D would be p = p.south(); The answer here is E Neighborhood The class Neighborhood represents a list of positions. The list is stored in an array apvector<position> mylist and can hold up to four positions. (Note an unfortunate clash of terms: the list stores elements of the type Position which represent positions on a 2-D grid; at the same time we are used to talking about the position of elements in an array.) The default constructor allocates room for four elements and sets mycount to 0 for an empty list. The Neighborhood class has the following member functions: void Add(const Position & pos); // Adds pos to the list Position Select(int index); // Returns pos stored in the element // numbered by index int Size(); // Returns the number of elements in the // list In addition, the ToString function is used for debugging printouts. Why do we need this class? It has to do with the overall layout of objects in Part 2 of the case study. A fish needs to know which neighboring positions are vacant in order to make its next move. The environment knows the locations of all fishes, but this information is private. The Neighborhood class provides a way to pass the information about vacant neighboring positions from the environment to a fish. The name Neighborhood may make this class look unnecessarily complicated or specialized. In fact, the way it is set up has nothing to do with neighbors: it is basically a general-purpose class that implements a list. It could be implemented as a reusable templated class that could work with any specified number of elements of any type. Such classes (known as container classes) are usually included in standard libraries of classes. This one expands on the apvector class: it supports the Add function and keeps track of how many elements are actually stored in the list. [ apstack or apqueue could potentially do the job here, too, but these are required only for the AB exam. ]

17 Chapter 6. Case Study CS Fish and Environment Things get more complicated as we move on to the higher-level classes. The Fish class and the Environment class are closely dependent on each other. This is to be expected: each fish interacts with its environment. You can see the first sign of this interdependence in the #includes: // environ.h #include "fish.h" // environ.cpp #include "environ.h" #include "fish.h" // fish.cpp #include "fish.h" #include "environ.h" (Some of these are redundant. Multiple includes of the same header file are prevented by using #ifndef conditional compilation directions in each header file. Otherwise fish.h would be included twice in environ.cpp and twice in fish.cpp, causing syntax errors.) The case study booklet explores conversations between a fish and the environment: who tells whom what and how. Basically, a fish knows that it has to move, if possible, into a randomly-chosen vacant neighboring cell (or stay put if there is nowhere to move). The environment knows which cells around the fish are vacant. The fish obtains this information from the environment and moves by updating its own position as stored within the fish object. Then it reports to the environment that it has moved so that the environment can update itself. We have to keep looking at these two classes together because they work closely with each other. We can start by first looking at their data members: // fish.h class Fish... int myid; Position mypos; bool amidefined; ; // environ.h class Environment... apmatrix<fish> myworld; // grid of fish int myfishcreated; // # fish ever created int myfishcount; // # fish in current environment ;

18 CS-16 Chapter 6. Case Study As we can see, both are quite limited. A fish is described by its ID tag and its position. It can also be defined or undefined. The environment is described by a 2-D array of fish myworld, the total number of fish myfishcount, and, for now a bit mysterious, myfishcreated. It is reasonable to assume that myfishcount is the number of fishes in the matrix that are defined and that empty cells are designated by undefined fishes. This will be confirmed shortly. The Environment class has one constructor: Environment(istream & input); It takes an open input stream (usually a file) as an argument, reads the data from the file, and initializes the environment s data members. It first reads the number of rows and columns in the matrix and resizes myworld accordingly (from an initially empty matrix). Here we have to pause for a moment and ask ourselves: What is placed into the elements of myworld in the process? There is no explicit initialization, but something happens to them behind the scenes. Recall that if an apvector or an apmatrix is constructed without an explicit fill value or if it is resized, the new elements are filled with something created by the element s default constructor. We have to go to fish.cpp and look at what Fish s default constructor does: Fish::Fish() : myid(0), amidefined(false) // postcondition: IsUndefined() == true Sure enough, it places false into the fish s amidefined flag. Thus, resize fills myworld with undefined fishes. Environment s constructor then reads the positions of fishes from the file and adds these fishes to myworld: while (input >> row >> col) AddFish(Position(row, col)); Note how a position is constructed from row, col and passed to AddFish as an argument in one statement. While we are at it, we might as well look at the AddFish function (this is the only place where it is used): void Environment::AddFish(const Position & pos) myfishcreated++; myworld[pos.row()][pos.col()] = Fish(myFishCreated, pos); myfishcount++;

19 Chapter 6. Case Study CS-17 This function creates a fish with a unique ID at the given position and places it into myworld: myworld[pos.row()][pos.col()] = Fish(myFishCreated, pos); Lots of things happen in this one statement: a fish is created with the given ID and position; the accessor functions Row() and Col() are called for pos and their return values are used as indices into the myworld array. We can also finally see here how myfishcreated is used: it is a unique ID value that is incremented before we add a new fish to myworld. In the case study, myfishcount and myfishcreated always have the same values after AddFish is done. But suppose in some other model we want to allow fish to die or leave the environment (decrementing myfishcount). Then it is handy to have two different data members, myfishcount and myfishcreated. We have to look at the Fish constructor with two arguments in order to understand exactly what is added to myworld: Fish::Fish(int id, const Position & pos) : myid(id), mypos(pos), amidefined(true) // postcondition: Location() returns pos, Id() returns id, // IsUndefined() == false In this constructor, the fish is defined (amidefined is set to true) and it gets the specified ID and position. Note that mypos(pos) uses a copy constructor for the Position class, which is not explicitly defined; member-by-member copy works for this class. We now continue with the Environment class. It has two accessor functions, NumRows() and NumCols(), that return the dimensions of myworld. It also has IsEmpty(pos), which returns true if pos is empty, and a private member function InRange(pos) that returns true if pos is within the dimensions of myworld. A more interesting function is AllFish(): it builds and returns an apvector<fish>, a list of all defined fishes in the environment. Skipping all the debugging printouts, it looks like this:

20 CS-18 Chapter 6. Case Study apvector<fish> Environment::AllFish( ) const // postcondition: returned vector (call it fishlist) contains all fish // in top-down, left-right order: // top-left fish in fishlist[0], // bottom-right fish in fishlist[fishlist.length()-1]; // # fish in environment is fishlist.length() apvector<fish> fishlist(myfishcount); int r, c; int count = 0; for (r = 0; r < NumRows(); r++) for (c = 0; c < NumCols(); c++) if (!myworld[r][c].isundefined()) fishlist[count] = myworld[r][c]; count++; return fishlist; This function is needed for three reasons: (1) it defines the order of processing the fishes as top-to-bottom, left-to-right; (2) it provides a way of passing a list of all fishes up to the Simulation class and to the Display class without copying the whole myworld matrix; and (3) it puts all fishes into temporary storage, which prevents processing those fishes that have already moved in the same step of the simulation. We cannot use myworld directly in other classes because it is a private member of Environment. Even if we could, we d have to be careful to keep track which fishes had already moved and which hadn t. But this function is expensive: not only does it scan through the whole matrix and builds the list, it also copies the list when it passes it to the calling function. All of the above is only background work for the actual simulation moving the fishes. The actual movement is implemented in three functions: Fish::EmptyNeighbors(...), Fish::Move(...), and Environment::Update(...) and this is where things get a bit convoluted. A fish might know how to swim, but it does not really know its neighbors, so it has to consult its environment, and it has to update the environment after it moves. We have little choice but to pass the environment to the Move function as an argument. The code of Move, stripped of the debugging statements, would look as follows:

21 Chapter 6. Case Study CS-19 void Fish::Move(Environment & env) // precondition: Fish stored in env // postcondition: Fish has moved to a new location in env (if possible) RandGen randomvals; // (See the comment about local variable randomvals in our review // of Part 1) Neighborhood nbrs = EmptyNeighbors(env, mypos); // Obtain a list of all vacant neighbors of this fish s position // from env if (nbrs.size() > 0) // If there are empty neighbors... Position oldpos = mypos; // Save the old fish s position mypos = nbrs.select(randomvals.randint(0, nbrs.size() - 1)); // Choose one of the neighbors randomly and // make it the new position of this fish. // (It could also be: // mypos = nbrs.select(randomvals.randint(nbrs.size()); // ) env.update(oldpos, *this); // Update the position of this fish from oldpos to its // current (new) pos in env The Update function, after we remove redundant checks, might look as follows: void Environment::Update(const Position & oldloc, Fish & fish) // precondition: fish was located at oldloc, has been updated // postcondition: if (fish.location()!= oldloc) then oldloc is empty; // Fish fish is updated properly in this environment Fish emptyfish; // Make an "undefined" fish Position newloc = fish.location(); // Obtain this fish s new position (stored in this fish) myworld[newloc.row()][newloc.col()] = fish; // Place this fish into its correct new location in myworld if (!(oldloc == newloc)) // If this fish indeed moved... myworld[oldloc.row()][oldloc.col()] = emptyfish; // Place an undefined fish into this fish s old location (For some reason, the previously used name oldpos suddenly becomes oldloc in this function in the case study code.) Note the use of!(oldloc == newloc) instead of!=. This is because the latter is not overloaded for the Position class. We could get by without the comparison altogether if we changed the order of statements:

22 CS-20 Chapter 6. Case Study void Environment::Update(const Position & oldpos, Fish & fish) Fish emptyfish; myworld[oldpos.row()][oldpos.col()] = emptyfish; Position newpos = fish.location(); myworld[newpos.row()][newpos.col()] = fish; 56 Which of the following functions would become less efficient if apmatrix<fish> myworld were eliminated and all defined fishes in the environment were stored in a list apvector<fish>? I. bool Environment::IsEmpty(const Position & pos) II. void Fish::Move(Environment & env) III. apvector<fish> Environment::AllFish() (A) (B) (C) (D) (E) I only II only I and II II and III I, II and III Without an apmatrix<fish> myworld, the function IsEmpty would have to scan the whole list to find out whether a given position was empty. Even if the list were sorted by position, isempty would still need to do a search of some kind (a binary search might be a reasonable option). In a matrix representation we can go directly to the given position in myworld and see whether the fish there is defined. So IsEmpty becomes less efficient. Move s code becomes shorter because it doesn t have to update the environment, but it calls EmptyNeighbors which calls AddIfEmpty which calls IsEmpty, so it slows down, too. AllFish becomes more efficient, because the list is already there and you don t have to scan the whole matrix to build it. The answer is C. It looks like we have untangled most of this case study! The only little thing that remains is char Fish::ShowMe() const // postcondition: returns a character that can make me visible if (1 <= Id() && Id() <= 26) return 'A' + (Id() - 1); return '*'; This function is used for the text-mode display and its code could be moved to the display functions (we have access to a fish s ID through the Fish::Id() accessor function). ShowMe returns characters 'A' through 'Z' for IDs from 1 to 26 respectively and '*' for any ID greater than 26.

23 Chapter 6. Case Study CS Simulation and Display The Simulation class is trivial: it does not have any data members, its constructor has no code, and it has only two member functions: one puts an environment through one simulation step, the other runs a specified number of steps. The Step function obtains a list of all fishes from the environment and then moves each fish. It is the AllFish function that defines the order of processing the fishes. If we wanted to process fishes in a different order, we would need to sort the list first. The Run function simply calls Step a specified number of times, and it seems redundant. Indeed, main never calls it. The Simulation class would be more useful if we had different (but related) types of environments, so that we could run simulations on them using the same Simulation class. Here, we could instead just put the Step function inside the Environment class. (But then it would no longer represent just an environment; we would have to come up with a more appropriate name.) The Display class provides a function for displaying all fishes in the given environment. The text display version does not need much of a class: there are no data members, the constructor is empty, and it has only one function, Show. In the graphics version, the Display class may be more involved, but this is not included in the AP exam. Display is not a friend of Environment (friends are not in the AP subset), so it cannot work directly with its data members. Instead, the Show function obtains a list of all fishes by calling AllFish. Fortunately, this function already produces the list in the right order, top-to-bottom, left-to-right. If it didn t, we would have to sort the list (remember the Sort function in utils?) before displaying the fishes. In the text display version, the display will be easier to read if you use a printable character (e.g., '.') instead of a space for an empty cell. According to the OOP philosophy, the environment should know how to display itself, so, strictly speaking, the Show function should have been in Environment, not in Display. If we are using graphics, there is the problem that the environment does not know anything about the machine s graphics display capabilities, so it has to depend on the kindness of strangers like the Display class. This class may also be convenient if we want to implement different types of displays for different purposes. For the text-only version, one free-standing function Show could do the job just as well. (Free-standing functions are considered contrary to the OOP spirit. Purists insist that main should be the only freestanding function in any project and that it should consist of one line that constructs one application object.)

24 CS-22 Chapter 6. Case Study 57 What would be the main advantage of moving the Show function that implements text-mode display from the Display class to the Environment class? (A) (B) (C) (D) (E) The Environment::AllFish function could be eliminated The Fish::ShowMe function could be eliminated The code of Show could be simplified The code of Show could become more efficient for large myworld matrices It would provide a useful tool for debugging printouts in Fish::Move for large number of fish A is false because AllFish is called in Simulation::Step as well. B is also false; while a call to Fish::ShowMe() potentially could be replaced with a call to Fish::Id() with the code for converting an integer ID into a display character moved into Show, this approach can be implemented as easily in Display::Show as in Environment::Show. C is true, but the simplification is rather minor. E is not quite true: it would provide a tool for debugging printouts, but this tool won t be very useful because it would generate too much output. In D, a call to AllFish will become unnecessary because we could work directly with the myworld matrix. In the original implementation we run a nested loop through all rows and columns three times on each step: once to form a list of all fish in Simulation::Step, second to form a list of all fish in Display::Show, and third to display each fish. In the modified design we will need to run it only twice, which may result in better performance. The answer is D main The main program opens a data file and creates an environment from it. It does not check whether it opened the data file successfully or not; if it cannot find the file, then the environment s constructor reports an error message and aborts the program. Then main creates a simulation object, prompts the user to enter a desired number of steps, and runs the simulation through these steps, displaying the environment after each step. The program reads a dummy string to rid the input stream of pending new line characters and to pause the display after each step.

25 Chapter 6. Case Study CS Appendix: Doing It From Scratch? The case study discusses many subtle design decisions and options by asking questions such as Does the EmptyNeighbors function belong in the Fish class (where it is actually placed) or in the Environment class? or Is the Simulation class necessary? But it never really addresses the basic question: Why do we need seven classes, nine modules, and 25 pages (over 1350 lines) of code to implement what is essentially the rather simple task of repeatedly moving some elements in a 2-D array to randomly-chosen vacant neighboring positions? Could a simpler implementation with, say, one class and far less code do the job? The main reason for this complex structure, with intertwined Fish and Environment classes and the additional Neighborhood class, is the OOP philosophy of smart objects. If we had several different types of fish or sea creatures in the same environment, then different creatures could be represented by different but related classes arranged in the same hierarchy. A member function with the same name, (e.g. Move or Swim) in each of these classes could implement swimming for this particular type of fish. Some could crawl and others could fly. The myworld matrix would contain pointers to different types of fish and the right function would be called for each type of fish automatically. This is possible in C++ due to a feature known as virtual functions and polymorphism (not in the AP subset). But in a simple case, our life would be much easier if some objects were just plain dumb and were told what to do and how to do it. For this particular simulation, OOP is overkill. No matter what the theory says, it is easier to design, write, debug, understand, maintain, and expand a program that uses one class with 200 lines of code than seven classes with 1300 lines. Exercise 8 on page 42 in the case study booklet asks: What are the advantages and disadvantages of designing and implementing your own code, as opposed to understanding and adapting the existing code? It depends, of course, on the quality of the code, whether there are any problems with it (e.g., it runs too slowly or it cannot be adapted to support new features), and on your software design and programming experience. In industry this question may be also decided according to the policies (and politics) of a given organization. You may be tempted to give it a shot and rewrite the whole thing. If you do, verify that your program produces exactly the same result as the case study program (when you seed the random number generator with the same seed). If you accomplish that, you can say that you have completely understood the case study code. If you don t want to do your own design, you can use the seamain.cpp and seafish.h provided here as a starting point and write your own seafish.cpp. Or see our seafish.cpp which completes the project.

26 // seamain.cpp #include <iostream.h> #include <fstream.h> #include "apstring.h" #include "seafish.h" void Show(const SeaFish &model); int main() apstring filename; int step, numsteps; cout << "Data file name: "; getline(cin, filename); #ifdef _MSC_VER // Use the nocreate flag For VC++ to prevent creating an empty file // when fish.dat is not found: ifstream file(filename.c_str(), ios::nocreate); #else ifstream file(filename.c_str()); #endif if (!file) cout << "Cannot open " << filename << endl; return 1; SeaFish model(file); cout << "Start:\n"; Show(model); cout << "Number of steps: "; cin >> numsteps; cin.ignore(1000, '\n'); for (step = 1; step <= numsteps; step++) model.step(); cout << "After step " << step << ":\n"; Show(model); cout << "Press <Enter> to continue...\n"; cin.ignore(1000, '\n'); return 0; //****************************************************************

27 void Show(const SeaFish &model) int rows = model.numrows(); int cols = model.numcols(); int row, col; Fish fish; char ch; cout << endl; for (row = 0; row < rows; row++) for (col = 0; col < cols; col++) fish = model.getfish(row, col); if (fish.state == EMPTY) ch = '.'; else if (fish.id > 26) ch = '*'; else ch = 'A' + fish.id - 1; cout << ch; cout << endl; cout << endl;

28 // seafish.h #ifndef _SEAFISH_H #define _SEAFISH_H #include <iostream.h> #include <apmatrix.h> enum STATE EMPTY, ALIVE, MOVED; struct Fish int id; STATE state; ; Fish(); Fish(int anyid); class SeaFish public: SeaFish(istream &input, bool randomseed = true); int NumRows() const; int NumCols() const; Fish GetFish(int row, int col) const; void Step(); // Move all fishes private: bool InRange(int row, int col) const; bool IsEmpty(int row, int col) const; void Move(int row, int col); // Move the fish at row, col ; apmatrix<fish> myworld; int myfishcreated; #endif

29 // seafish.cpp #include <time.h> #include <stdlib.h> #include "seafish.h" // for time() // for rand/srand int RandomInt(int n) return int(rand() / (double(rand_max) + 1) * n); //**************************************************************** Fish::Fish() : id(0), state(empty) Fish::Fish(int anyid) : id(anyid), state(alive) //**************************************************************** SeaFish::SeaFish(istream &input, bool randomseed) : myfishcreated(0), myworld(0,0) int rows, cols, row, col; input >> rows >> cols; myworld.resize(rows, cols); while (input >> row >> col) myfishcreated++; myworld[row][col] = Fish(myFishCreated); if (randomseed) srand(unsigned(time(0))); // Seed random number generator // from system time int SeaFish::NumRows() const return myworld.numrows(); int SeaFish::NumCols() const return myworld.numcols(); bool SeaFish::InRange(int row, int col) const return 0 <= row && row < NumRows() && 0 <= col && col < NumCols(); bool SeaFish::IsEmpty(int row, int col) const return InRange(row, col) && myworld[row][col].state == EMPTY; Fish SeaFish::GetFish(int row, int col) const return myworld[row][col];

30 void SeaFish::Move(int row, int col) apmatrix<int> neighbor(2,4); // Holds positions of empty neighbors int n, count = 0; int newrow, newcol; Fish emptyfish; // Examine four neighbors and collect empty neighbors: if (IsEmpty(row-1, col)) // North neighbor[0][count] = row-1; neighbor[1][count] = col; count++; if (IsEmpty(row+1, col)) // South neighbor[0][count] = row+1; neighbor[1][count] = col; count++; if (IsEmpty(row, col+1)) // East neighbor[0][count] = row; neighbor[1][count] = col+1; count++; if (IsEmpty(row, col-1)) // West neighbor[0][count] = row; neighbor[1][count] = col-1; count++; // Move fish to a randomly selected empty neighbor: if (count > 0) n = RandomInt(count); // Better (but would produce a result different from the case study): // if (count > 1) n = RandomInt(count); // else n = 0; newrow = neighbor[0][n]; newcol = neighbor[1][n]; myworld[newrow][newcol] = myworld[row][col]; myworld[newrow][newcol].state = MOVED; myworld[row][col] = emptyfish; void SeaFish::Step() int row, col; // Move all fishes: for (row = 0; row < NumRows(); row++) for (col = 0; col < NumCols(); col++) if (myworld[row][col].state == ALIVE) Move(row, col); // Restore the state of all moved fishes to ALIVE: for (row = 0; row < NumRows(); row++) for (col = 0; col < NumCols(); col++) if (myworld[row][col].state == MOVED) myworld[row][col].state = ALIVE;

AP Computer Science. Marine Biology Teacher s Manual. Supplement to the Marine Biology Case Study. Advanced Placement Program

AP Computer Science. Marine Biology Teacher s Manual. Supplement to the Marine Biology Case Study. Advanced Placement Program AP Computer Science Marine Biology Teacher s Manual Supplement to the Marine Biology Case Study Advanced Placement Program 1 This Teacher s Manual is intended for use by AP teachers for course and exam

More information

AP Computer Science. Marine Biology Case Study. Appendices. Advanced Placement Program

AP Computer Science. Marine Biology Case Study. Appendices. Advanced Placement Program AP Computer Science Marine Biology Case Study Appendices Advanced Placement Program 10/11/2001 These appendices are intended for use by AP teachers for course and exam preparation in the classroom; permission

More information

AP Computer Science AB 2002 Free-Response Questions

AP Computer Science AB 2002 Free-Response Questions AP Computer Science AB 2002 Free-Response Questions The materials included in these files are intended for use by AP teachers for course and exam preparation in the classroom; permission for any other

More information

2003 AP COMPUTER SCIENCE AB FREE-RESPONSE QUESTIONS

2003 AP COMPUTER SCIENCE AB FREE-RESPONSE QUESTIONS COMPUTER SCIENCE AB SECTION II Time 1 hour and 45 minutes Number of questions 4 Percent of total grade 50 Directions: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE WRITTEN IN C++. Note:

More information

Marine Biology Simulation Case Study

Marine Biology Simulation Case Study Marine Biology Simulation Case Study Chapter 4 Specialized Fish After I demonstrated the dynamic population version of the simulation to the marine biologists to make sure it met their needs, we talked

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

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

For Teacher's Use Only Q No Total Q No Q No

For Teacher's Use Only Q No Total Q No Q No Student Info Student ID: Center: Exam Date: FINALTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Time: 90 min Marks: 58 For Teacher's Use Only Q No. 1 2 3 4 5 6 7 8 Total Marks Q No. 9

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

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

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #43 Multidimensional Arrays In this video will look at multi-dimensional arrays. (Refer Slide Time: 00:03) In

More information

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team

Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Page. No. 1/15 CS201 Introduction to Programmming Solved Subjective Questions From spring 2010 Final Term Papers By vuzs Team Question No: 1 ( Marks: 2 ) Write a declaration statement for an array of 10

More information

1 Dynamic Memory continued: Memory Leaks

1 Dynamic Memory continued: Memory Leaks CS104: Data Structures and Object-Oriented Design (Fall 2013) September 3, 2013: Dynamic Memory, continued; A Refresher on Recursion Scribes: CS 104 Teaching Team Lecture Summary In this lecture, we continue

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved Chapter Four: Loops Slides by Evan Gallagher The Three Loops in C++ C++ has these three looping statements: while for do The while Loop while (condition) { statements } The condition is some kind of test

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017

More information

Preprocessor Directives

Preprocessor Directives C++ By 6 EXAMPLE Preprocessor Directives As you might recall from Chapter 2, What Is a Program?, the C++ compiler routes your programs through a preprocessor before it compiles them. The preprocessor can

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Here's how you declare a function that returns a pointer to a character:

Here's how you declare a function that returns a pointer to a character: 23 of 40 3/28/2013 10:35 PM Violets are blue Roses are red C has been around, But it is new to you! ANALYSIS: Lines 32 and 33 in main() prompt the user for the desired sort order. The value entered is

More information

(Refer Slide Time 3:31)

(Refer Slide Time 3:31) Digital Circuits and Systems Prof. S. Srinivasan Department of Electrical Engineering Indian Institute of Technology Madras Lecture - 5 Logic Simplification In the last lecture we talked about logic functions

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

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

CSE 333 Midterm Exam July 24, Name UW ID#

CSE 333 Midterm Exam July 24, Name UW ID# Name UW ID# There are 6 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS

LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS LAB 5, THE HIDDEN DELIGHTS OF LINKED LISTS Questions are based on the Main and Savitch review questions for chapter 5 in the Exam Preparation section of the webct course page. In case you haven t observed

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Practice Final Examination #2

Practice Final Examination #2 Eric Roberts Handout #54 CS106B March 11, 2013 Practice Final Examination #2 Review session: Sunday, March 17, 3:00 5:00 P.M. (Hewlett 200) Scheduled finals: Tuesday, March 19, 12:15 3:15 P.M. (Hewlett

More information

ASSIGNMENT 4 Classes and Objects

ASSIGNMENT 4 Classes and Objects ASSIGNMENT 4 Classes and Objects COMP-202A, Fall 2010, All Sections Due: Friday, November 19, 2010 (23:55) You MUST do this assignment individually and, unless otherwise specified, you MUST follow all

More information

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination University of Illinois at Urbana-Champaign Department of Computer Science First Examination CS 225 Data Structures and Software Principles Spring 2007 7p-9p, Thursday, March 1 Name: NetID: Lab Section

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Student Performance Q&A:

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

More information

PRACTICE MIDTERM EXAM #2

PRACTICE MIDTERM EXAM #2 This practice exam is based on the actual midterm exam from Cynthia s Spring 2014 class. It did not include a classes problem (which you should expect this quarter), and the memory/pointers problem covered

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

Function Call Stack and Activation Records

Function Call Stack and Activation Records 71 Function Call Stack and Activation Records To understand how C performs function calls, we first need to consider a data structure (i.e., collection of related data items) known as a stack. Students

More information

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02) Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 04 Lecture - 01 Merge Sort (Refer

More information

Lecture Notes on Contracts

Lecture Notes on Contracts Lecture Notes on Contracts 15-122: Principles of Imperative Computation Frank Pfenning Lecture 2 August 30, 2012 1 Introduction For an overview the course goals and the mechanics and schedule of the course,

More information

Animations involving numbers

Animations involving numbers 136 Chapter 8 Animations involving numbers 8.1 Model and view The examples of Chapter 6 all compute the next picture in the animation from the previous picture. This turns out to be a rather restrictive

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

ENCM 369 Winter 2017 Lab 3 for the Week of January 30

ENCM 369 Winter 2017 Lab 3 for the Week of January 30 page 1 of 11 ENCM 369 Winter 2017 Lab 3 for the Week of January 30 Steve Norman Department of Electrical & Computer Engineering University of Calgary January 2017 Lab instructions and other documents for

More information

(Refer Slide Time: 02.06)

(Refer Slide Time: 02.06) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 27 Depth First Search (DFS) Today we are going to be talking

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

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd

19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd 19 Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd Will you walk a little faster? said a whiting to a snail, There s a porpoise close behind us, and he s treading

More information

AP Computer Science A 2003 Scoring Guidelines

AP Computer Science A 2003 Scoring Guidelines AP Computer Science A 2003 Scoring Guidelines The materials included in these files are intended for use by AP teachers for course and exam preparation; permission for any other use must be sought from

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Computer Programming Basic Control Flow - Loops Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons Objectives To learn about the three types of loops: while for do To avoid infinite

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

These are notes for the third lecture; if statements and loops.

These are notes for the third lecture; if statements and loops. These are notes for the third lecture; if statements and loops. 1 Yeah, this is going to be the second slide in a lot of lectures. 2 - Dominant language for desktop application development - Most modern

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Collected By Anonymous

Collected By Anonymous CS201- Introduction to Programming Mega Collection for Final Term Only Solved Paper Year Session Paper # 01 2012 Unknown Paper # 02 2011 (session_02) Paper # 03 2011 (session_03) Paper # 04 2010 Unknown

More information

In either case, remember to delete each array that you allocate.

In either case, remember to delete each array that you allocate. CS 103 Path-so-logical 1 Introduction In this programming assignment you will write a program to read a given maze (provided as an ASCII text file) and find the shortest path from start to finish. 2 Techniques

More information

PAIRS AND LISTS 6. GEORGE WANG Department of Electrical Engineering and Computer Sciences University of California, Berkeley

PAIRS AND LISTS 6. GEORGE WANG Department of Electrical Engineering and Computer Sciences University of California, Berkeley PAIRS AND LISTS 6 GEORGE WANG gswang.cs61a@gmail.com Department of Electrical Engineering and Computer Sciences University of California, Berkeley June 29, 2010 1 Pairs 1.1 Overview To represent data types

More information

D Programming Language

D Programming Language Group 14 Muazam Ali Anil Ozdemir D Programming Language Introduction and Why D? It doesn t come with a religion this is written somewhere along the overview of D programming language. If you actually take

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

6.001 Notes: Section 15.1

6.001 Notes: Section 15.1 6.001 Notes: Section 15.1 Slide 15.1.1 Our goal over the next few lectures is to build an interpreter, which in a very basic sense is the ultimate in programming, since doing so will allow us to define

More information

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm

Assignment3 CS206 Intro to Data Structures Fall Part 1 (50 pts) due: October 13, :59pm Part 2 (150 pts) due: October 20, :59pm Part 1 (50 pts) due: October 13, 2013 11:59pm Part 2 (150 pts) due: October 20, 2013 11:59pm Important Notes This assignment is to be done on your own. If you need help, see the instructor or TA. Please

More information

Getting started with simulating data in R: some helpful functions and how to use them Ariel Muldoon August 28, 2018

Getting started with simulating data in R: some helpful functions and how to use them Ariel Muldoon August 28, 2018 Getting started with simulating data in R: some helpful functions and how to use them Ariel Muldoon August 28, 2018 Contents Overview 2 Generating random numbers 2 rnorm() to generate random numbers from

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

CS 61B, Midterm #3 and solutions, Spring 1996

CS 61B, Midterm #3 and solutions, Spring 1996 CS61B (Clancy) Spring 1996 Exam 3, solutions, and grading standards. April 12, 1996 Exam 3 Read and fill in this page now. Do NOT turn the page until you are told to do so. Your name: Your login name:

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

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

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Mastering Data Abstraction or Get nit-picky on design advantages

Mastering Data Abstraction or Get nit-picky on design advantages Arizona s First University. Mastering Data Abstraction or Get nit-picky on design advantages Luke: Your not my father! Vader: You mean, You re not my father Luke: What? Vader: You used the possessive,

More information

CS 142 Style Guide Grading and Details

CS 142 Style Guide Grading and Details CS 142 Style Guide Grading and Details In the English language, there are many different ways to convey a message or idea: some ways are acceptable, whereas others are not. Similarly, there are acceptable

More information

Chapter Four: Loops II

Chapter Four: Loops II Chapter Four: Loops II Slides by Evan Gallagher & Nikolay Kirov Chapter Goals To understand nested loops To implement programs that read and process data sets To use a computer for simulations Processing

More information

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00)

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00) Assignment 4 Aggregate Objects, Command-Line Arguments, ArrayLists COMP-202B, Winter 2011, All Sections Due: Tuesday, March 22, 2011 (13:00) You MUST do this assignment individually and, unless otherwise

More information

(Refer Slide Time 6:48)

(Refer Slide Time 6:48) Digital Circuits and Systems Prof. S. Srinivasan Department of Electrical Engineering Indian Institute of Technology Madras Lecture - 8 Karnaugh Map Minimization using Maxterms We have been taking about

More information

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview

Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring Topic Notes: C and Unix Overview Computer Science 2500 Computer Organization Rensselaer Polytechnic Institute Spring 2009 Topic Notes: C and Unix Overview This course is about computer organization, but since most of our programming is

More information

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms

Introduction to Linked Lists. Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Introduction to Linked Lists Introduction to Recursion Search Algorithms CS 311 Data Structures and Algorithms Lecture Slides Friday, September 25, 2009 Glenn G. Chappell Department of Computer Science

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

Matrices. Chapter Matrix A Mathematical Definition Matrix Dimensions and Notation

Matrices. Chapter Matrix A Mathematical Definition Matrix Dimensions and Notation Chapter 7 Introduction to Matrices This chapter introduces the theory and application of matrices. It is divided into two main sections. Section 7.1 discusses some of the basic properties and operations

More information

How & Why We Subnet Lab Workbook

How & Why We Subnet Lab Workbook i How & Why We Subnet Lab Workbook ii CertificationKits.com How & Why We Subnet Workbook Copyright 2013 CertificationKits LLC All rights reserved. No part of this book maybe be reproduced or transmitted

More information

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

6. Pointers, Structs, and Arrays. March 14 & 15, 2011 March 14 & 15, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

4. Java Project Design, Input Methods

4. Java Project Design, Input Methods 4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

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

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

To become familiar with array manipulation, searching, and sorting.

To become familiar with array manipulation, searching, and sorting. ELECTRICAL AND COMPUTER ENGINEERING 06-88-211: COMPUTER AIDED ANALYSIS LABORATORY EXPERIMENT #2: INTRODUCTION TO ARRAYS SID: OBJECTIVE: SECTIONS: Total Mark (out of 20): To become familiar with array manipulation,

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

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

C Functions. 5.2 Program Modules in C

C Functions. 5.2 Program Modules in C 1 5 C Functions 5.2 Program Modules in C 2 Functions Modules in C Programs combine user-defined functions with library functions - C standard library has a wide variety of functions Function calls Invoking

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

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

Project and Production Management Prof. Arun Kanda Department of Mechanical Engineering Indian Institute of Technology, Delhi

Project and Production Management Prof. Arun Kanda Department of Mechanical Engineering Indian Institute of Technology, Delhi Project and Production Management Prof. Arun Kanda Department of Mechanical Engineering Indian Institute of Technology, Delhi Lecture - 8 Consistency and Redundancy in Project networks In today s lecture

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Memory Addressing, Binary, and Hexadecimal Review

Memory Addressing, Binary, and Hexadecimal Review C++ By A EXAMPLE Memory Addressing, Binary, and Hexadecimal Review You do not have to understand the concepts in this appendix to become well-versed in C++. You can master C++, however, only if you spend

More information

Taskbar: Working with Several Windows at Once

Taskbar: Working with Several Windows at Once Taskbar: Working with Several Windows at Once Your Best Friend at the Bottom of the Screen How to Make the Most of Your Taskbar The taskbar is the wide bar that stretches across the bottom of your screen,

More information

PRACTICE FINAL EXAM 3

PRACTICE FINAL EXAM 3 This practice exam is based on an actual final exam from CS106X (same topics coverage as CS106B, but somewhat higher expectations for mastery). The question types and mix of topics of our CS106B exam will

More information