CS201 – Introduction to Computing – Sabancı University 1 First Midterm Exam l November 25, 2006, Saturday, 10:40 – 12:20, max 100 minutes l Exam Places.

Slides:



Advertisements
Similar presentations
Summer Computing Workshop. Introduction to Variables Variables are used in every aspect of programming. They are used to store data the programmer needs.
Advertisements

CS201 – Introduction to Computing – Sabancı University 1 First Midterm Exam l November 22, 2008, Saturday, 10:40 – 12:20, max 100 minutes l One A4 size.
Announcements Homework 4 – Robot game is assigned Due NEXT WEEK on Wednesday 26 th November  Start EARLY! Common Questions: Be aware of the flow of the.
Computer Science 1620 Loops.
Computer Science 1620 Programming & Problem Solving.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
C++ fundamentals.
Classes in C++ Bryce Boe 2012/08/15 CS32, Summer 2012 B.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CS201 – Introduction to Computing – Sabancı University 1 Announcements l General rules about homeworks ä Use of global variables (variables defined outside.
Classes: From Use to Implementation
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Announcements Midterm is TOMORROW! On August 2 nd Tuesday at 19:40 (~ 100 minutes) in FENS L045 Today at 14:30-17:30 there is an extra recitation in FENS.
CS201 – Introduction to Computing – Sabancı University 1 Announcements l General rules about homeworks ä Use of global variables (variables defined outside.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 3.0.
Chapter 8 Friends and Overloaded Operators. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Friend Function (8.1) Overloading.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Announcements HW3 grades will be announced this week HW4 is due this week Final exam on August 25, 2010, Wednesday at 09:00 Duration is about 140 minutes.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Using, Understanding, Updating, Designing and Implementing Classes Chapters 5 (5.4) and partially 6 and 7 in Chapter 6, up to in Chapter 7 concepts.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Programming Principles Chapter 1. Objectives Discuss the program design process. Introduce the Game of Life. Discuss object oriented design. – Information.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
Agenda Object Oriented Programming Reading: Chapter 14.
CPS120: Introduction to Computer Science Lecture 14 Functions.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Announcements Midterm1 is on this Tuesday at 19:40. Classrooms as follows: if (LastName
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Loops Wrap Up 10/21/13. Topics *Sentinel Loops *Nested Loops *Random Numbers.
Summary of what we learned last week Classes How to use classes/objects Header (.h) and implementation (.cpp) files String class Member functions: length,
C++ Classes and Data Structures Jeffrey S. Childs
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
1 CSC 222: Computer Programming II Spring 2004  classes and objects  abstract data types, classes and objects  using existing classes, #include, member.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
CS201 – Introduction to Computing – Sabancı University 1 Using, Understanding, Updating, Designing and Implementing Classes l Chapters 5 (5.4) and partially.
A Computer Science Tapestry 6.1 Classes: From Use to Implementation l We’ve used several classes, a class is a collection of objects sharing similar characteristics.
CS 106 Introduction to Computer Science I 03 / 22 / 2010 Instructor: Michael Eckmann.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
Announcements HW2 is due on Wednesday this week. HW3 will be assigned this week, will be due next week.
CPSC 252 ADTs and C++ Classes Page 1 Abstract data types (ADTs) An abstract data type is a user-defined data type that has: private data hidden inside.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Classes and OOP.
Announcements Homework 5 – Robot game will be assigned this week
About the Presentations
Announcements Homework 5 – Robot game will be assigned this week
Introduction to Classes
Announcements Homework 3 – Robot game will be assigned this Friday
User-Defined Functions
Announcements Homework 5 – Robot game will be assigned this week
Introduction to Classes
Using, Understanding, Updating, Designing and Implementing Classes
Announcements HW2 is due on Wednesday this week.
Chapter 9 Introduction To Classes
Presentation transcript:

CS201 – Introduction to Computing – Sabancı University 1 First Midterm Exam l November 25, 2006, Saturday, 10:40 – 12:20, max 100 minutes l Exam Places if (lastname <= "Asmazoğlu" ) cout << "FASS G022"; else if (lastname <= "Bıyık") cout << "FASS G049"; else if (lastname <= "Çayırlı") cout << "FASS G052"; else if (lastname <= "Gürcan") cout << "FASS G062 amfi"; else if (lastname <= "Karahan") cout << "FENS G035"; else if (lastname <= "Mutluel") cout << "FENS L045"; else if (lastanme <= "Vural") cout << "FENS G077 amfi"; else if (lastname <= "Zoroğlu") cout << "FENS L055";

CS201 – Introduction to Computing – Sabancı University 2 First Midterm Exam l One A4 size cheat-note allowed (both sides could be used) l Closed book, closed notes, no calculators and no laptops l Until the end of loops ä up to 5.4 from book (excluding 4.6.3) ä but you are responsible everything covered in class even if not covered in book e.g. robot class (all member functions; not only the ones you used in hw) several examples l Problem set and solutions are up on the web

CS201 – Introduction to Computing – Sabancı University 3 Using, Understanding, Updating, Designing and Implementing Classes l Chapters 5 (5.4) and partially 6 and 7 ä in Chapter 6, up to ä in Chapter 7 concepts of 7.1 and 7.2 are explained, but different examples are given l Robot class implementation details

CS201 – Introduction to Computing – Sabancı University 4 An Overview of Object Oriented (OO) Programming l In OO programming Data and Functions for a specific concept combined together ä called a “class” gives the general definition ä provides reusability change the values of data and you end up with different objects with the same functionality ä can be used by several applications

CS201 – Introduction to Computing – Sabancı University 5 An Overview of Object Oriented (OO) Programming l An example without OO programming - Calendar display program ä needs several utilities leap year check day of week function … day day of week month MonthName leap year year Data Functions... l Is this structure complex? ä for some yes, for some no

CS201 – Introduction to Computing – Sabancı University 6 An Overview of Object Oriented (OO) Programming l OO version - Calendar display program ä Date concept is developed as a class data and functions combined together from the point of view of programmer l Did you like this? ä for some yes, for some no l OO approach is more suitable for a human being ä human cognition is mostly based on objects Data Functions Day of the week Month name …

CS201 – Introduction to Computing – Sabancı University 7 Using classes (Section 5.4) l Another way of looking at OO programming ä Using only string, int, and double limits the kinds of programs we can write (games, calendars, …) ä why don’t we have off-the-shelf components for programming? l Using object-oriented techniques means we develop new types that correspond to the real-world objects we’re writing code for ä for example an online roulette game ä another example: checker game, pişti ä some write for us and we use them off-the-shelf components l New types are called classes, variables are called objects l User defined classes ä Tapestry Classes: classes written by Owen Astrachan (author of our book) for educational and practical purposes BigInt and other classes (like Date and Dice) that we will see ä Robot Class is not a Tapestry class, but it is a user-defined one

CS201 – Introduction to Computing – Sabancı University 8 The class Date The class Date is accessible to client programmers #include " date.h " to get access to the class The compiler needs this information. It may also contain documentation for the programmer  Link the implementation in date.cpp Add this cpp to your project The class Date models a calendar date:  Month, day, and year make up the state of a Date object  Date s can be printed, compared to each other, day-of- week determined, # days in month determined, many other behaviors Behaviors are called methods or member functions

CS201 – Introduction to Computing – Sabancı University 9 Constructing Date objects – see usedate.cpp Date today; Date republic(10,29,1923); Date million( ); Date y2k(1,1,2000); cout << "today: " << today << endl; cout << "Republic of Turkey has been founded on: " << republic << endl; cout << "millionth day: " << million << endl; OUTPUT today: November Republic of Turkey has been founded on: October millionth day: November

CS201 – Introduction to Computing – Sabancı University 10 Constructing/defining an object Date objects (like string objects) are constructed when they’re first defined  Three ways to construct a Date default constructor, no params, initialized to today’s date single long int parameter, number of days from January 1, 1 three params: month, day, year (in this order). What happens if values are wrong (e.g. month is 15)? Constructors for Date objects look like function calls ä constructor is special member function ä Different parameter lists mean different constructors Once constructed, there are many ways to manipulate a Date ä Increment it using ++, subtract an int from it using -, print it using cout, …  MonthName(), DayName(), DaysIn(), … l See date.h for more info on date constructors and member functions

CS201 – Introduction to Computing – Sabancı University 11 Date Member Functions Date MidtermExam(11,25,2006);  Construct a Date object given month, day, year MidtermExam.DayName() ä Returns the name of the day (“Saturday” or “Sunday”, or...) in this particular case, returns “Saturday” since November 25,2006 is a Saturday MidtermExam.DaysIn() ä Returns the number of days in the particular month in our case return 30, since November 2006 has 30 days in it l Add, subtract, increment, decrement days from a date Date GradesDue = MidtermExam + 7; ä GradesDue is December 2, 2006 l Let’s see usedate.cpp in full and datedemo.cpp now

CS201 – Introduction to Computing – Sabancı University 12 Example: Father’s day (not in book) l Father’s day is the third Sunday of June ä write a function that returns the date for the father’s day of a given year which is the parameter of the function ä In main, input two years and display father’s days between those years Date fathersday(int year) // post: returns fathers day of year { Date d(6,1,year); // June 1 while (d.DayName() != "Sunday") { d += 1; } // d is now the first Sunday, third is 14 days later return d + 14; } l See fathersday.cpp for full program

CS201 – Introduction to Computing – Sabancı University 13 What if there were no date class? l It would be very cumbersome to deal with dates without a date class ä imagine banking applications where each transaction has associated date fields l Classes simplify programming ä they are designed and tested. ä then they can be used by programmers l You are lucky if you can find ready-to-use classes for your needs ä otherwise ???

CS201 – Introduction to Computing – Sabancı University 14 The class Dice l Computer simulated dice ä not real dice, but have same functionality random number between 1 and number of sides ä in this class, we can have dice objects with any number of sides Accessible to client programmers using #include " dice.h " ä Why are quotes used instead of angle brackets ? l Dice objects will work as pseudo-random number generators ä Not truly random in a strict mathematical sense ä Still useful to introduce randomness into programs

CS201 – Introduction to Computing – Sabancı University 15 The class Dice l A small class ä better to show basic implementation details on a small example l State ä number of sides ä roll count l Member functions Dice(int sides); // constructor – constructs a die with given number of sides int Roll(); // return the random roll int NumSides() const; // how many sides int NumRolls() const; // # of times this die rolled

CS201 – Introduction to Computing – Sabancı University 16 Using the class Dice cout << "rolling " << cube.NumSides() << " sided die" << endl; cout << cube.Roll() << endl; cout << "rolled " << cube.NumRolls() << " times" << endl; member functions Dice cube(6); // construct six-sided die Dice dodeca(12); // construct twelve-sided die See roll.cpp for full program constructor

CS201 – Introduction to Computing – Sabancı University 17 What you can and cannot do with Dice l Cannot define a Dice object without specifying # sides ä Not a bug, just a design decision ä You may modify the class implementation to have a default constructor (will see later) Dice d(2); // ok, like a coin Dice cube; // NOT ok, won’t compile How random is a Dice object – how can we test this? ä Calculate number of rolls needed to obtain a target sum repeat this several times and find the average in order to approach to the expected value ä repeat for all target values between 2 and 12 using two 6-sided dice ä Any expectations? Needs probability knowledge. ä See testdice.cpp

CS201 – Introduction to Computing – Sabancı University 18 Classes: From Use to Implementation (Chapter 6.1) l We’ve used several classes, a class is a collection of objects sharing similar characteristics  A class is a type in C++, like int, bool, double ä A class encapsulates state and behavior string (this is a standard class), needs #include ä Objects: " hello ", " there are no frogs ", …  Methods: substr(…), length(…), find(…), operators such as + and << Date needs #include " date.h " ä Objects: December 7, 1949, November 22, 1963  Some Methods: MonthName(), DaysIn(), operator - etc.

CS201 – Introduction to Computing – Sabancı University 19 State and Behavior l Behavior of a class is what a class does ä described in verbs babies eat, cry dice are rolled ä In OO programming terminology, behaviors are defined by public member functions for Dice class, member functions are the Dice constructor, NumRolls(), NumSides() and Roll() l State of a class depends on physical properties ä cats have four legs, different eye colors ä dice have a number of sides ä In OO programming, State is defined by private data in the header file also called member data, instance variables, or data fields for Dice class, mySides and myRollCount (see dice.h)

CS201 – Introduction to Computing – Sabancı University 20 Anatomy of the Dice class The class Dice, need #include " dice.h " ä Objects: six-sided dice, 32-sided dice, one-sided dice  Methods: Roll(), NumSides(), NumRolls() l A Dice object has state and behavior ä Each object has its own state, just like each int has its own value Number of times rolled, number of sides l All objects in a class share method implementations, but access their own state  How to respond to NumRolls()? Return my own # rolls

CS201 – Introduction to Computing – Sabancı University 21 The header file dice.h class Dice { public: Dice(int sides); // constructor int Roll(); // return the random roll int NumSides() const; // how many sides int NumRolls() const; // # times this die rolled private: int myRollCount; // # times die rolled int mySides; // # sides on die }; The compiler reads this header file to know what’s in a Dice object Each Dice object has its own mySides and myRollCount ä generally initialized by the constructor function

CS201 – Introduction to Computing – Sabancı University 22 The header file is a class declaration l Private data are called instance variables (a.k.a. data members) ä each object has its own private data l Public functions are called methods, member functions, these are called by client programs ä All objects of a particular class share the method implementations l The header file is an interface, not an implementation ä Description of behavior, analogy to DVD player Do you know how DVD player operates? You do not mind, just press the button (interface) and watch! ä Square root button, how does it calculate? Do you care? l Provides information to compiler and to programmers ä Compiler determines what methods/member functions can be called for a class/object ä Programmer reads header file to determine what methods are available, how to use them, other information about the class

CS201 – Introduction to Computing – Sabancı University 23 What to know? l Client programmer (programmer who uses the classes) needs to know the interface from the header file ä public member functions and constructors how they behave ä does not need to know private data (instance variables) ä does not need to know how the member functions are implemented just need to know where (in which file) it is implemented in order to include the implementation file in the project l As a good programmer who will design and/or update classes, YOU may need to know about the class implementations

CS201 – Introduction to Computing – Sabancı University 24 From interface to use, the class Dice #include "dice.h" int main() { Dice cube(6); Dice dodeca(12); Objects constructed cube.myRollCount  0 cube.mySides  6 dodeca.myRollCount  0 dodeca.mySides  12 Method invoked cube.myRollCount  1 cube.mySides  6 After for loop dodeca.myRollCount  6 dodeca.mySides  12 cout << cube.Roll(); int k; for(k=0; k < 6; k++) { cout << dodeca.Roll(); } return 0; }

CS201 – Introduction to Computing – Sabancı University 25 From Interface to Implementation l The header file provides compiler and programmer with how to use a class, but no information about how the class is implemented ä Important separation of concerns, use without complete understanding of implementation l Implementation file is a cpp file with no main function ä member function and constructor bodies are given sometimes some other functions are also given

CS201 – Introduction to Computing – Sabancı University 26 Implementation: the.cpp file l In the implementation file we see all member functions written, similar idea as functions we’ve seen so far ä Each function has name, parameter list, and return type ä A member function’s name includes its class type class_name :: function_name (params) ä A constructor is a special member function for initializing an object, constructors have no return type class_name :: class_name (params) :: is the scope resolution operator specifies the class of the function l Each method can access private data members of an object (the object on which this member function will operate) ä In this way, at each invocation, member function may access different objects’ private data cube.NumSides() compared to dodeca.NumSides() ä dot operator. is used when a member function is called

CS201 – Introduction to Computing – Sabancı University 27 dice.cpp (Implementation file) – 1/2 Dice::Dice(int sides) // postcondition: all private fields initialized { myRollCount = 0; mySides = sides; } int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; } Constructor

CS201 – Introduction to Computing – Sabancı University 28 dice.cpp (Implementation file) – 2/2 int Dice::NumRolls() const // postcondition: return # of times die has been rolled { return myRollCount; } int Dice::Roll() // postcondition: number of rolls updated // random 'die' roll returned { RandGen gen; // random number generator (“randgen.h”) myRollCount= myRollCount + 1; // update # of rolls return gen.RandInt(1,mySides); // in range [1..mySides] }

CS201 – Introduction to Computing – Sabancı University 29 Understanding Class Implementations l Private data members are global such that ä they are accessible by all class member functions  e.g. in the implementation of Roll function, mySides and myRollCount are not defined but used because they are private data

CS201 – Introduction to Computing – Sabancı University 30 Understanding Class Implementations l Constructors should assign values to each instance variable ä this is what construction is ä not a rule, but a good programming style

CS201 – Introduction to Computing – Sabancı University 31 Understanding Class Implementations l Methods (member functions) can be broadly categorized as accessors or mutators ä Accessor methods return information about an object but do not change the state Dice::NumRolls() and Dice::NumSides() ä Mutator methods change the state of an object Dice::Roll(), since it changes an object’s myRollCount

CS201 – Introduction to Computing – Sabancı University 32 Class Implementation Heuristics l All data should be private ä Provide accessor functions as needed Make accessor functions const  by putting const after all parameters  A const function cannot modify the state of an object precaution against poor implementations compilers do not allow to update private data int Dice::NumSides() const // postcondition: return # of sides of die { return mySides; }

CS201 – Introduction to Computing – Sabancı University 33 Updating a Class (not in book) l Suppose you want to add more functionality to the date class ä need to change the header file (date.h) ä need to add implementation of new function(s) to date.cpp l Example: a new member function to calculate and return the remaining number of days in the object’s month ä any ideas? do you think it is too difficult? ä have a look at the existing member functions and see if they are useful for you

CS201 – Introduction to Computing – Sabancı University 34 Updating a Class (not in book) We can make use of DaysIn member function l Prototype in Date class (add to the header file) int Date::RemainingDays () const; l Implementation int Date::RemainingDays () const { return DaysIn() - myDay; } l In a member function implementation private data and other member functions referred without the dot operator. ä They operate on the object for which the member function is called

CS201 – Introduction to Computing – Sabancı University 35 Updating a Class (not in book) Example use of RemainingDays Date today; cout << "There are " << today.RemainingDays() << " days left in the current month" << endl; l See date_modified.h, date_modified.cpp and demodatemodified.cpp When RemainingDays is called,  call to DaysIn is for today since it is the object on which RemainingDays is called  myDay is today’s myDay since it is the object on which RemainingDays is called

CS201 – Introduction to Computing – Sabancı University 36 RandGen Class l A Tapestry class for random number generation l Add randgen.cpp to your project and #include “randgen.h” l Four member functions int RandInt(int max = INT_MAX);  returns a random integer in [0..max) int RandInt(int low, int max);  returns a random integer in [low..max] double RandReal();  returns a random double value in [0..1) double RandReal(double low, double max); ä returns a random double value in the range of [low..max] There are two different functions named RandInt  so as RandReal l Using the same name for more than one function is called overloading. They are differentiated by parameter types and/or return types. All member and free functions can be overloaded. l see numberguess.cpp for an example program that use RandGen

CS201 – Introduction to Computing – Sabancı University 37 Implementation of Robot Class - 1 l Your next homework will be about updating the Robot class ä you will add some more member functions that requires to deal with robots.h and robots.cpp files ä and you use those newly added functions in an application l It is a good idea to have a look at how this class is implemented ä It is designed and implemented by Ersin Karabudak I have made some changes later l Robot class implementation is quite complex ä Robot, RobotWindow and RobotWorld are different structures we will not deal with RobotWindow and RobotWorld, but robots.cpp implementation file contains robot class implementation and the details of RobotWindow and RobotWorld too. Do not get confused. ä Robots are maintained as a circular doubly linked list it is a data structure that uses pointers (probably will see in CS202) but do not get thrilled! you will not need those complex structures for the member functions that you will add. l Some details you have to know will be given now and more details will be given in recitations this week

CS201 – Introduction to Computing – Sabancı University 38 Implementation of Robot Class - 2 enum Direction { east, west, north, south }; enum Color { white, yellow, red, blue, green, purple, pink, orange }; class Robot { public: Robot (int x, int y, Direction dir = east, int things = 0); ~Robot (); void Move (int distance = 1); bool Blocked (); void TurnRight (); bool PickThing (); bool PutThing (); void SetColor (Color color); bool FacingEast (); bool FacingWall (); bool CellEmpty (); bool BagEmpty (); constructor Destructor (not needed in HW5) member functions continued on the next slide

CS201 – Introduction to Computing – Sabancı University 39 Implementation of Robot Class - 3 private: int xPos; //x coordinate of the location of robot int yPos; //y coordinate of the location of robot Direction direction; //current direction of robot Color color; //current color of robot int bag; //current # of things in the bag of robot bool stalled; //true if the robot is dead bool visible; //true if the robot is visible Robot *next; Robot *prev; static Robot *list; friend struct RobotWindow; }; Private Data pointers for the data structure you will not need them RobotWindow may refer Robot’s private data

CS201 – Introduction to Computing – Sabancı University 40 Implementation of Robot Class - 4 l Previous two slides were in the robots.h. l Now let’s go over the robots.cpp file in VC++ environment l In the next homework, you are going to add 9 member functions to the robot class ä 2-3 of them will be done in recitations this week l Hints for the next homework (to be assigned this week) ä try to use currently available member functions e.g. for PickAll, try to use PickThing in a loop rather than writing some thing similar to PickThing ä do not hesitate to modify or access private data members when needed e.g. you will need such an update for Turn function ä if you change the state of a robot within the current cell, use the following to update the window theRobotWindow->Redraw(this);

CS201 – Introduction to Computing – Sabancı University 41 Implementation of Robot Class - 5 l Hints for the next homework (cont’d)  you will need to use the function called IsPressed defined in miniFW.h (it is going to be renamed as miniFW_modified.h) so include this header file to your main program file this function ( IsPressed ) is to check whether a key (e.g. an arrow key) is pressed or not - details are in recitations  You will need to use the functions GetCellCount and GetThingCount To learn the amount of things in a cell and in a particular area – details are in recitations ä Three new member functions are added to the Robot class BeamUp, InPrison, NonEmptyNeighborExists You will need to use them – details are in recitations l Some other changes in the Robot World and Robot Class ä If a robot hits another robot, both die! ä Now the bag content is written in robots (if not zero)

CS201 – Introduction to Computing – Sabancı University 42 Design Heuristics l What is an heuristic? ä a set of guidelines and policies may not be perfect, but mostly useful exceptions are possible ä e.g. making all state data private is an heuristic ä we will see two more class design heuristics cohesion and coupling l Make each function or class you write as single-purpose as possible ä Avoid functions that do more than one thing, such as reading numbers and calculating an average, standard deviation, maximal number, etc., If source of numbers changes how do we do statistics? If we want only the average, what do we do? ä Classes should embody one concept, not several. ä This heuristic is called Cohesion, we want functions and classes to be cohesive, doing one thing rather than several Easier to re-use in multiple contexts

CS201 – Introduction to Computing – Sabancı University 43 Design Heuristics continued (Coupling) l Coupling: interactions among functions and classes l Functions and classes must interact to be useful ä One function calls another  One class uses another, e.g., as the Dice::Roll() function uses the class RandGen l Keep interactions minimal so that classes and functions don’t rely too heavily on each other, we want to be able to change one class or function (to make it more efficient, for example) without changing all the code that uses it l Some coupling is necessary for functions/classes to communicate, but keep coupling loose and be aware of them

CS201 – Introduction to Computing – Sabancı University 44 Designing classes from scratch l Chapter 7 (especially 7.1 and 7.2) ä a good development strategy “iterative enhancement” approach ä READ those sections, you are responsible we won’t cover all, because it takes too much time and becomes boring! ä I will give a simpler class design example here less iterative but similar application

CS201 – Introduction to Computing – Sabancı University 45 Implementing Classes l It is difficult to determine what classes are needed, how they should be implemented, which functions are required ä Experience is a good teacher, failure is also a good teacher Good design comes from experience, experience comes from bad design ä Design and implementation combine into a cyclical process: design, implement, re-visit design, implement, test, redesign, … Grow a working program, don’t do everything at the same time

CS201 – Introduction to Computing – Sabancı University 46 Design and Implementation Heuristics l A design methodology says that “look for nouns, those are classes”, and then “look for verbs and scenarios, those are member functions” l Not every noun is a class, not every verb is a method ä some functions will be free ones or will be implemented in main (these are design decisions), l Concentrate on behavior (member functions) first when designing classes, then on state (private part) ä private data will show its necessity during the implementation of the public part

CS201 – Introduction to Computing – Sabancı University 47 Example class design l Quiz class ä simple quiz of addition questions l Scenarios ä user is asked a number of questions ä computer asks random questions ä user enters his/her answer correct / not correct feedback and correct answer are displayed ä correct answers are counted l can be two classes ä question ä quiz l but I will have one class which is for question and implement quiz in main ä Be careful! This example is similar but different than the one in book (7.1 and 7.2)

CS201 – Introduction to Computing – Sabancı University 48 Question class l Question behaviors (verbs). A question is ä created ä asked ä answered ä checked l These are candidate member functions ä more? less? we will see l A question is simply two random integers (to keep it simple say between 1 and 100) to be added ä those numbers are definitely in class private data ä what else? we will see

CS201 – Introduction to Computing – Sabancı University 49 Question class l simplemathquest.h (first draft) class Question { public: Question(); // create a random question void Ask() const; // ask the question to user int GetAnswer() const; //input and return user answer bool IsCorrect(int answer) const; //check if correct private: int myNum1; // numbers used in question int myNum2; };

CS201 – Introduction to Computing – Sabancı University 50 Quiz program (main - simplequiz.cpp) – Draft int qNum = PromptRange("how many questions: ",1,5); int k, ans, score =0; for(k=0; k < qNum; k++) { Question q; q.Ask(); ans = q.GetAnswer(); if (q.IsCorrect(ans)) { cout << ans << " correct answer" << endl << endl; score++; } else { cout << "Sorry, not correct. Correct answer was " << ???????? << endl << endl; } } cout << "Score is " << score << " out of " << qNum << " = " << double(score)/qNum * 100 << "%" << endl; l Something missing: a function to return the correct result

CS201 – Introduction to Computing – Sabancı University 51 Question class l simplemathquest.h (second draft) class Question { public: Question(); // create a random question void Ask() const; // ask the question to user int GetAnswer() const; //input and return user answer bool IsCorrect(int answer) const; //check if correct int CorrectAnswer() const; //return the correct answer private: int myNum1; // numbers used in question int myNum2; };

CS201 – Introduction to Computing – Sabancı University 52 Quiz program (simplequiz.cpp) – Final int qNum = PromptRange("how many questions: ",1,5); int k, ans, score =0; for(k=0; k < qNum; k++) { Question q; q.Ask(); ans = q.GetAnswer(); if (q.IsCorrect(ans)) { cout << ans << " correct answer" << endl << endl; score++; } else { cout << "Sorry, not correct. Correct answer was " << q.CorrectAnswer() << endl << endl; } cout << "Score is " << score << " out of " << qNum << " = " << double(score)/qNum * 100 << "%" << endl;

CS201 – Introduction to Computing – Sabancı University 53 Question class implementation l simplemathquest.cpp (draft 1) void Question::Ask() const { cout << myNum1 << " + " << myNum2 << " = "; } int Question::GetAnswer() const { int ans; cin >> ans; return ans; } Question::Question() { RandGen gen; myNum1 = gen.RandInt(1,100); myNum2 = gen.RandInt(1,100); } constructor

CS201 – Introduction to Computing – Sabancı University 54 Question class implementation l simplemathquest.cpp (draft 1) - continued l Problem: Where is the correct answer stored? ä a new private data field would be good bool Question::IsCorrect(int answer) const { return ?????? == answer; } int Question::CorrectAnswer() const { return ??????; }

CS201 – Introduction to Computing – Sabancı University 55 Question class l simplemathquest.h (final) class Question { public: Question(); // create a random question void Ask() const; // ask the question to user int GetAnswer() const; //input and return user answer bool IsCorrect(int answer) const; //check if correct int CorrectAnswer() const; //return the correct answer private: int myNum1; // numbers used in question int myNum2; int myAnswer; // store the answer };

CS201 – Introduction to Computing – Sabancı University 56 Question class implementation l simplemathquest.cpp (final) Question::Question() { RandGen gen; myNum1 = gen.RandInt(1,100); myNum2 = gen.RandInt(1,100); myAnswer = myNum1 + myNum2; } void Question::Ask() const { cout << myNum1 << " + " << myNum2 << " = "; } int Question::GetAnswer() const { int ans; cin >> ans; return ans; }

CS201 – Introduction to Computing – Sabancı University 57 Question class implementation l simplemathquest.cpp (final) - continued bool Question::IsCorrect(int answer) const { return myAnswer == answer; } int Question::CorrectAnswer() const { return myAnswer; }

CS201 – Introduction to Computing – Sabancı University 58 Thinking further l What about a generic question class ä not only addition, but also other arithmetic operations may need another private variable for the operation that is also useful to display the sign in Ask may need parameter in the constructor (for question type) will do this week in recitations l What about questions for which answers are strings? ä maybe our generic question class should have string type answers to serve not only to arithmetic questions but any type of questions see Sections 7.1 and 7.2