Programming I EECS 168
Popular in Course
verified elite notetaker
History 105 Fry- Roots of Contemporary Issues
verified elite notetaker
verified elite notetaker
verified elite notetaker
Popular in Elect Engr & Computer Science
verified elite notetaker
This 42 page Class Notes was uploaded by Melissa Metz on Monday September 7, 2015. The Class Notes belongs to EECS 168 at Kansas taught by Donna Haverkamp in Fall. Since its upload, it has received 17 views. For similar materials see /class/186774/eecs-168-kansas in Elect Engr & Computer Science at Kansas.
Reviews for Programming I
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/07/15
Iterative Statements The while Statement Counting Loops Conditional Loops In nite Loop Errors The for Statement Autoincrement and Autodecrement Operators The dowhile Statement Nested Loops Common Errors Software Engineering Tips The while Statement 0 Often need to do repetitive calculations to solve problems Computers are good at this humans are typically bad at this A while loop can be used to iteratively execute a block of code Need to specify the following 1 the code to execute before loop 2 the Boolean condition for continuing iteration 3 the block of code to be repeated 0 The program will execute block of code over and over as long as the Boolean condition remains TRUE Code after the loop is executed when condition becomes FALSE While loop syntax initialization code while Boolean expression block of statements to be repeated update variables in Boolean expression Counting Loops o Often need to perform an operation xed number of times 0 Counting loops allow us to do this 0 Need to do the following 1 initialize the loop counter 2 while counter has NOT reached desired number 0 perform desired operations 0 increment loop counter 0 check loop counter again Counting loop example int count 0 while count lt 10 cout ltlt count ltlt quotsquaredquot ltlt countcount ltlt endl count count l Zero iterations loop int value 42 while value lt 42 cout ltlt value ltlt quotdoubledquot ltlt value2 ltlt endl value value l Conditional Loops We can vary the number of iterations based on the data values Conditional loops process data until given situation arises Can also be used to check for end of input or invalid data values Need to do the following 1 perform initialization code 2 while condition remains TRUE the program 0 perform desired operations 0 check terminating condition again Conditional loop example int amt 99 int pow 0 while amt gt O cout ltlt quotamtquot ltlt amt ltlt quot powquot ltlt pow ltlt endl amt amt2 pow pow 1 cout ltlt quotamtquot ltlt amt ltlt quot powquot ltlt pow ltlt endl Input varying loop int num cout ltlt quotEnter a number use 1 to endnquot cin gtgt num while num gt 0 val sqrtnum cout ltlt val ltlt quotsquaredquot ltlt num ltlt endl cout ltlt quotEnter a number use 1 to endnquot cin gtgt num Calculate sum of variable number of values int count 0 int sum 0 int num cout ltlt quotEnter sequence of values use 1 to endnquot cin gtgt num while num gt 0 count count 1 sum sum num cin gtgt num Calculate and print average if count gt O cout ltlt quotAverage quot ltlt sum count ltlt endl else cout ltlt quotNo data enterednquot Infinite Loop Errors 0 It is possible to create while loops that execute forever 0 Often these in nite loops are often unplanned and unwanted 0 To get out of in nite loop you need to kill your program using quotC o Occasionally in nite loops are used on purpose this is not recommended but you may see it in other programmer39s code Trivial in nite loop example while true cout ltlt quotHello Momnquot Accidental in nite loop example int total 0 int count 0 while count lt 10 total total count missing count increment In nite loop caused by an IO error code will execute forever if a character is typed as input instead of a number height 0 while height lt 42 cout quotEnter height quot cin gtgt height The for Statement 0 The for loop provides a compact syntax for iteration 0 Typically used for counting loops but can be used for any loop 0 Allows you to specify the following all on one line 1 initialization statements 2 Boolean expression for continuing loop 3 statements to be executed after loop For loop syntax for initialization Boolean expression increment statements to be repeated For loop example for int num O num lt 10 num numl cout ltlt num ltlt quotcubedquot ltlt numnumnum ltlt endl Autoincrement and Autodecrement Operators o The and operators add or subtract one to a variable 0 rewrite i il as i o rewritej jl asj 0 Similar short form combines assignment and operators 0 rewriteaabasab o rewriteccdascd o rewriteaab asab o rewriteccdascd o rewriteaab asab o Produces shorter and often faster code Example using compact operators int sum 0 int product l for int count 0 count lt 13 count sum count product count Assign rst then increment int num 5 int val num now val is 5 num is 6 Increment rst then assign int num 5 int val num now nal is 6 num is 6 The dowhile Statement The dowhile loop puts Boolean expression after the body of loop Body will be always executed at least once If Boolean expression is TRUE the loop will continue Useful for selected applications Example read input and check if valid Do while example int value do cout ltlt quotEnter a number between 09 quot cin gtgt value while value lt 0 value gt 9 Nested Loops o Often necessary for one loop to include another loop 0 Need separate initializations Boolean expressions and increments o If the outer loop executes N times and the inner loop executes M times then the inner loop body is executed N x M times Square printing example for int height0 height lt 14 height Outer loop code for int width0 width lt 17 width Inner loop code cout ltlt quotquot cout ltlt endl Factorial example for int number 1 number lt 42 number Outer loop code int factorial l for int count 1 count lt number count Inner loop code factorial count cout ltlt quotNumber quot ltlt number ltlt quotFactorial quot ltlt factorial ltlt endl Common Errors Extra semicolon after for or while causes logic error Counters and other variables not properly initialized Boolean expression will never become FALSE in nite loop Loop executes incorrect number of times off by one common Never update for loop counter variable inside for loop Never use same counter variable for nested loops Incorrect nested loop example int index for index 0 index lt 10 index for index 0 index lt 10 index cout ltlt quotResult quot ltlt 3 index 5 ltlt endl cout ltlt quotIndex quot ltlt index ltlt endl Software Engineering Tips 0 Print debugging messages inside each loop to count loop iterations and show values of important variables 0 Anticipate that loops may execute zero times and make sure that all variables are initialized and code runs properly 0 Anticipate and avoid in nite loops by making sure you get quotcloserquot to the loop terminating condition after each loop iteration Fibonacci Example 0 Output the Fibonacci sequence 1 1 2 3 5 8 13 21 Invented 100s of years ago to model population growth Do you notice the pattern First two values are equal to one Following values are the sum of the previous two values Initial Fibonacci Program Purpose Program to print 9 Fibonacci numbers Solution without iteration using 9 variables Author John Gauch include ltiostreamgt using namespace std int main Output rst two values int numl 1 cout ltlt numl ltlt endl int num2 1 cout ltlt num2 ltlt endl Calculate and output remaining values int num3 numl num2 cout ltlt num3 ltlt endl int num4 num2 num3 cout ltlt num4 ltlt endl int num5 num3 num4 cout ltlt num5 ltlt endl int num6 num4 num5 cout ltlt num6 ltlt endl int num7 num5 num6 cout ltlt num7 ltlt endl int num8 num6 num7 cout ltlt num8 ltlt endl int num9 num7 num8 cout ltlt num9 ltlt endl return 0 Intermediate Fibonacci Program Purpose Program to print 9 Fibonacci numbers Solution without iteration using 3 variables Author John Gauch include ltiostreamgt using namespace std int main Output rst two values int numl l cout ltlt numl ltlt endl int num2 l cout ltlt num2 ltlt endl Calculate and output remaining values using repeated code int num3 numl num2 cout ltlt num3 ltlt endl numl num2 num2 num3 num3 numl num2 cout ltlt num3 ltlt endl numl num2 num2 num3 num3 numl num2 cout ltlt num3 ltlt endl numl num2 num2 num3 num3 numl num2 cout ltlt num3 ltlt endl numl num2 num2 num3 num3 numl num2 cout ltlt num3 ltlt endl numl num2 num2 num3 num3 numl num2 cout ltlt num3 ltlt endl numl num2 num2 num3 num3 numl num2 cout ltlt num3 ltlt endl return 0 Final Fibonacci Program Purpose Program to print 9 Fibonacci numbers Solution with iteration Author John Gauch include ltiostreamgt using namespace std int main Output rst two values int num1 1 cout ltlt num1 ltlt endl int num2 1 cout ltlt num2 ltlt endl Calculate and output remaining values using iteration int count 3 while count lt 9 int num3 num1 num2 cout ltlt num3 ltlt endl num1 num2 num2 num3 count count 1 Inheritance Motivation De ning Person Class De ning Student Class Using Person and Student Classes Sample Program Output Implementing Person Methods Implementing Student Methods Constructor Functions Destuctor Functions Shape Inheritance Hierarchy University Inheritance Hierarchy Closing Comments Motivation Code reuse is an important bene t to object oriented programming We can de ne classes that contain objects of other classes For example a polygon class that contains N point objects We can also classes by extending the de nition of other classes This process is called inheritance The base class contains general purpose datamethods The derived class contains more specialized datamethods Defining Person Class 0 We can de ne a Person with typical methodsdata 0 Nothing extra needs to be done to support inheritance Person class de nition class Person Methods public Person Person string GetName string GetAddress void SetNamestring name void SetAddressstring address void Print Data private string Name string Address int Age Defining Student Class 0 We can de ne a Student by extending the Person class Only need to de ne the additional methodsdata Student has access to all public Person methodsdata Student does not have access to private methodsdata We can also rede ne methods if desired eg Print The program will automatically call correct methods Student class de nition class Student public Person Methods public Student Studentstring name string address oat gpa Student oat GetGPA void SetGPA oat gpa void Print Data private oat GPA Using Person and Student Classes Main program int main Declare and initialize Person object Person p p SetName Bob Brown p SetAddress 123 Somewhere Street pSetGPA20 error pPrint Declare and initialize Student object Student s s SetName Sam Smith s SetAddress 456 Nowhere Lane sSetGPA395 sPrint cout ltlt Donenn Destructors called automatically Sample Program Output Name Bob Brown Address 123 Somewhere Street Name Sam Smith Address 456 Nowhere Lane GPA 395 Done Destroying Student Name Sam Smith Address 456 Nowhere Lane GPA 395 Destroying Person Name Sam Smith Address 456 Nowhere Lane Destroying Person Name Bob Brown Address 123 Somewhere Street Implementing Person Methods 0 Methods have normal access to private Person data 0 Should provide get set methods for derived classes string Person GetNameO return Name string Person GetAddress return Address void Person SetNamestring name Name name void Person SetAddressstring address Address address void Person Print cout ltlt quotName quot ltlt Name ltlt quot Address quot ltlt Address ltlt endl Implementing Student Methods 0 Methods have normal access to private Student data 0 Must use getset methods to access private Person data oat Student GetGPA return GPA void Student SetGPA oat gpa GPA gpa void StudentPrint cout ltlt quotName quot ltlt GetName ltlt quot Address quot ltlt GetAddress ltlt quot GPA quot ltlt GPA ltlt endl Constructor Functions 0 The constructor function for a derived class will automatically call the constructor function for all base classes 0 This will let you initialize all private variables of an object 0 There are also more complex ways to specify default values see the text book for details Person Person Initialize Person data Name quotquot Address quotquot Student Student Person constructor called automatically Initialize Student data GPA 00 Student Studentstring name string address oat gpa Person constructor called automatically Initialize Person data via get set methods SetNamename SetAddressaddress Initialize Student data GPA gpa Destructor Functions 0 The destructor function for a derived class will automatically call the destructor function for all base classes 0 This will let you close les or delete memory as needed when you are nished using an object Person Person Debug message Cout ltlt Destroying Personn Print Clear data Name Address Student Student Debug message Cout ltlt Destroying Studentn Print Clear data GPA 00 Person destructor called automatically Shape Inheritance Hierarchy 0 Consider the following object hierarchy o What methodsdata belong with each object o How can inheritance be used to de ne these classes Shape Obj ect2D Circle Square Triangle Obj ect3D Cube Sphere Tetrahedron University Inheritance Hierarchy 0 Consider the following object hierarchy o What methodsdata belong with each object o How can inheritance be used to de ne these classes UniversityMember Employee Faculty Administrator Teacher Staff Student Graduate Undergraduate Alumnus Closing Comments 0 Inheritance can be a powerful tool for software design and code reuse 0 C provides several other object oriented programming features that are not discussed in this section 0 Protected datamethods 0 Multiple inheritance o Polymorphism 0 Virtual functions Pointers and Dynamic Structures Overview of Memory Model Pointer Variables Using Dynamic Variables and Arrays Using Dynamic Structures and Arrays of Structures Reference Parameters Revisited Class Constructors Copy Constructors Class Destructors Overview of Memory Model o Computer memory can be viewed as an quotarrayquot of storage locations o On a PC this array may be limited to size of physical memory o On a workstation quotvirtualquot memory size is almost unlimited o Memory at run time typically contains the following Free The 0s 0s Memory Heap Code Data Program Program The Code Data Stack 1 operating system code o The 08 code is loaded into memory when machine quotbootsquot o This code is executed when 0 S functions are called 2 operating system data o Provides space for all global variables of the O S o On some systems this data may be on the stack 3 program code o The program code is loaded when the program is quotinvokedquot o The code is executed when program functions are called 4 program data o Provides space for all global variables of the program o On some systems this data may be on the stack 5 the stack o Provides space for all parameters and local variables in functions o Space is dynamically allocated when a function is called o Space is dynamically released when a function returns o The stack also contains the return address for function calls o The stack is essential for supporting recursive functions 6 the heap o Provides space for all dynamically allocated variables o Space is specifically requested by programmer o Space is specifically released by programmer o The heap is essential for supporting advanced data structures such as 0 variable length arrays linked lists trees and graphs 7 free memory o Free memory is located between the stack and the heap o Free memory gives the stack and the heap room to grow 0 quotstack over owquot occurs when too much stack space is requested 0 quotallocation errorquot occurs when too much heap space is requested Pointer Variables o All program variables start at some memory location in the computer o Pointer variables contain the starting addresses of other variables o Can access variables quotindirectlyquot using pointers o Need to be very careful about how and when we use pointers Declarations oat value 42 oat gt temp NULL Pointer initialization temp ampva1ue Direct variable access value 77 cout ltlt value Indirect variable access gt temp 94 cout ltlt gt temp Using Dynamic Variables and Arrays o Pointers can also contain addresses of space requested from the heap o Must specify amount of space needed number amp types of variables Different data types are different sizes char1 int4 oat4 etc o This mechanism gives us a way to create variable sized arrays o The new command creates space the delete command releases space o Use gt data or datai to access dynamic variables or arrays o Use delete or delete to return memory to the heap Allocate a dynamic variable int gt value NULL value new int Using a dynamic variable gt value 13 delete value int gt john new int cout ltlt gt john Allocate a dynamic array int size cout ltlt quotEnter size of arrayquot cin gtgt size oat gt data new oatsize Use the dynamic array for int i0 i lt size i datai i 314159 size delete data Using Dynamic Structures and Arrays of Structures o Can also request space for one or more structures on the heap o This is used for creating linked lists trees and graphs o Must de ne structure and use new and delete as before o Need to use datagtPart or dataPart to refer to subparts Allocate a dynamic structure struct student char Name20 int Year oat GPA student gt temp new student student junk junkYear 2006 Using a dynamic structure strcpytempgtName quotTom J onesquot tempgtYear 2006 tempgtGPA 3 0 Allocate a dynamic array of structures int size cout ltlt quotEnter size of arrayquot cin gtgt size student gt data new studentsize Initialize dynamic array of structures for int i0 i lt size i strcpydatai Name quot quot dataiYear 2006 dataiGPA 00 cin gtgt size Point gt p new Pointsize for int i0 iltsize i pisetX rand lOO pisetY rand 100 Use dynamic array of structures student gt ptr NULL for int i0 i lt size i if strcmpdataiName quotJohn Smithquot 0 ptr datai if ptr NULL ptrgtGPA 35 Release memory delete temp delete data Reference Parameters Revisited o When we pass a variable by reference we really pass its address o When we access a reference parameters are really using indirection o In C this method of parameter passing was explicit o In C reference parameters are simpler to de ne and use C function with reference parameters void fooint ampnum num num 42 Corresponding C function call int val 1101 foo val C function with reference parameters Expects the address of an integer as an argument void barint gtl num gtl num num l7 Corresponding C function call Passes the address of an integer to function int val 1304 bar ampval Class Constructors o The constructor function is called when a class variable is declared o This function has the same name as the class itself o Constructor initializes private data members of the class o Dynamic size objects can be created using the new command Array class de nition class Array public Arrayint size constructor Arrayconst amp Array copy constructor Array destructor void ReadArraychar f11ename void ProcessArrayint param void WriteArraychar f11ename private int Length int gt Data Constructor function Array Arrayconst int size Length size Data new intLength Write array data to le void Array WriteArraychar lename ofstream dout 1ename for int i0 iltLength i dout ltlt Datai ltlt quot quot dout ltlt endl doutclose Main program int main 1nt Slze cin gtgt size Array asize aReadArrayquotin letxtquot aProcessArray42 aWriteArrayquotout letxtquot magic call to a destructor Copy Constructors 0 The copy constructor is used to create copies of objects o It is also used when objects are passed by value into functions 0 Important to de ne when dynamic memory is allocated in constructor 0 Without a copy constructor dynamic objects should be passed by reference or you will have a shallow copy deep destroy bug Copy constructor function Array Arrayconst Array amp a Allocate space and make copy Length aLength Data new intLength for inti O i lt Length i Datai aDatai Usage example Array alOO aReadArrayquotinfiletxtquot Array ba Class Destructors o The destructor function is automatically called when the object is no longer in scope This function has the same name as the class with a added in front Destructor cleans up anything the class initialized or allocated Must make sure to free space using destroy in a destructor function Failure to clean up after new will eventually result in heap over ow Destructor function Array Array Length O delete Data
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'