Lecture 1 -- 1 Computer Science I - Martin Hardwick Making the bank object oriented rIn upcoming lectures we will be looking at efficiency issues rIn order.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick How do Calculators Computer Square Roots? rWhen you enter 29 into your calculator and push the square.
Advertisements

Lecture Computer Science I - Martin Hardwick Other Types Of Data rVariables of type short use half a word (16 bits) to represent a value. l everything.
Lecture Computer Science I - Martin Hardwick Odds And Ends – Switch Statement rIt is often necessary in programs to set up a set of cases, where.
Lecture Computer Science I - Martin Hardwick Searching and sorting rReasons for not using the most efficient algorithm include: l The more efficient.
Lecture Computer Science I - Martin Hardwick Bubble Sort bool bubble_once( vector &list, int top) // Perform one bubble iteration on a list { bool.
Lecture Computer Science I - Martin Hardwick Streams In C++ rA stream is a sequence that you either read from or write to. l example – cin is a stream.
Lecture Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays.
Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Lecture Computer Science I - Martin Hardwick Bank Simulation (1) #include using namespace std; // Create bank account data type struct acct { //
Lecture Computer Science I - Martin Hardwick Merge Sort Algorithm rMerge sort has two phases. l First it divides the data into smaller and smaller.
1 Using Classes and Working With Class Interfaces November 20, 2002 CSE103 - Penn State University Prepared by Doug Hogan.
1 Lab Session-XII CSIT121 Fall 2000 b Namespaces b Will This Program Compile ? b Master of Deceit b Lab Exercise 12-A b First Taste of Classes b Lab Exercise.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Computer Programming 1 Functions. Computer Programming 2 Objectives Take a first look at building functions Study how a function is called Investigate.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
Computer Science 1620 Programming & Problem Solving.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
1 Techniques of Programming CSCI 131 Lecture 29 Search.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
CS161 Topic #21 CS161 Introduction to Computer Science Topic #2.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
February 11, 2005 More Pointers Dynamic Memory Allocation.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Object-Oriented Programming in C++
Starting Out with C++, 3 rd Edition 1 Searching an Arrays.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
CSCI-383 Object-Oriented Programming & Design Lecture 5.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
Linked Lists part 2 CS 244 Brent M. Dingle, Ph.D. Game Design and Development Program Department of Mathematics, Statistics, and Computer Science University.
1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 2 Overloaded Operators, Class Templates, and Abstraction Jeffrey S. Childs Clarion University.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
C++ Classes and Data Structures Jeffrey S. Childs
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
11-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Chapter 2 part #1 C++ Program Structure
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Data Structures & Algorithms
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
Function Overloading Two different functions may have the same name as long as they differ in the number or types of arguments: int max(int x, int y) and.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 29 Thanks for Lecture Slides:
11 Introduction to Object Oriented Programming (Continued) Cats.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
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.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
Computer Science Department Data Structure and Algorithms Lecture 3 Stacks.
CS162 - Topic #10 Lecture: Recursion –The Nature of Recursion –Tracing a Recursive Function –Work through Examples of Recursion Programming Project –Discuss.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Linked Lists Data Structures and Algorithms CS 244 Brent M. Dingle, Ph.D. Department of Mathematics, Statistics, and Computer Science University of Wisconsin.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 C++ Classes and Data Structures Course link…..
Data Structure and Algorithms
Programs written in C and C++ can run on many different computers
Presentation transcript:

Lecture Computer Science I - Martin Hardwick Making the bank object oriented rIn upcoming lectures we will be looking at efficiency issues rIn order to study these issues we need implement the banking example as classes and vectors rBy making these changes we will be able to swap algorithms for the bank functions and measure efficiency. rThe two things we need to do are l Change the acct struct into an object l Make the bank a class that stores its data in a vector

Lecture Computer Science I - Martin Hardwick Making the struct an object rWe want to convert this struct to an object rAn object has data and methods rAn object has public and private sections rGood practice puts the data in the private rGood practice puts access methods also known as get and put methods in the public section rAfter we have done the conversion we can add other methods to the object. rFor example add_funds (double amount) is_bankrupt() struct acct { int acctnum; string name; double balance; };

Lecture Computer Science I - Martin Hardwick Account Class r Contents of the acct.h file #include class acct { public: acct (); acct (int num, string name, double bal); string get_name (); int get_acctnum (); double get_balance (); double put_balance (double bal); private: int acctnum; string name; doublebalance; }; rThere must be a corresponding account.cpp file with the member functions’ implementations. rThe ‘acct’ functions create the object. One with default values and the other with new values rThe get functions return each of the values. rThe put function allows the balance to be changed. rThe semi-colon at the end of the class is very important

Lecture Computer Science I - Martin Hardwick Acct implementation r Contents of the acct.cpp file #include #include “acct.h” double acct::get_bal () { return balance; } void acct::put_balance (double bal) { balance = bal; return; } string acct::get_name () { return name; } void acct::put_name (string nme) { name = nme; return; } rA method is a function that starts with the name of the class followed by “::”. acct::get_bal l is a method of the acct class rA get method returns the value. rA put method changes the value. rNormally there are gets and puts for every data item rYou MUST use the :: notation or the method will not belong to your class. l It will be an ordinary function that cannot access the member data l So you will see compiler errors complaining about undefined variables.

Lecture Computer Science I - Martin Hardwick Constructor methods r More contents of the acct.cpp file // default for constructor for arrays etc. acct:acct () { acctnum = -1; name = “unknown”; balance = 0; } // sensible constructor for new values acct:acct (int num, string nme, double bal) { acctnum = num; name = nme; balance = bal; } rA constructor method has the same name as the class. rConstructor methods are used to set initial values for the object. rThere has to be a constructor that takes no arguments. l This constructor is used to fill arrays and other data structures rUsually there is at least one other constructor that sets initial values for all the private data. rThe default constructor should set the private data to values that show the data has not yet been set l Our example sets the acctnum to -1

Lecture Computer Science I - Martin Hardwick Bank Simulation (banking.h) #include #include “acct.h” using namespace std; class banking { private: vector bank;// bank accounts public: banking (); int find(int goal); void insert(acct newacct); int size ();// current size of the bank acct get (int loc);// account at a location }; rNext we will make a class for the bank rThis class wraps the functions that we made before so that we can find and insert bank accounts. rWe also have a function to return a bank account instance after it has been found using the find function rA vector is used to hold the list of bank accounts. rA bank account consists of an account number, the name of the person who owns it, and the current balance. l Our new C++ class does this

Lecture Computer Science I - Martin Hardwick Bank Simulation (2) #include “banking.h” int main () //PURPOSE: simulate a small bank //PRECONDITIONS: existing // accounts in file account.txt // in project folder //POSTCONDITIONS: finds, inserts, // deletes, and lists accounts { // list of bank accounts banking my_bank; // file with list of bank accounts ifstreamvault; // user request stringcommand; // account number to find intgoal; rThe main function creates the list of bank accounts and processes user commands to perform transactions. rThe number of accounts is unlimited. rThe existing accounts are read from a file at the start of the program. l this creates the bank vector for the program to use rUser commands are typed as strings (e.g., find, insert, exit).

Lecture Computer Science I - Martin Hardwick Bank Simulation (3) // subscript of account in bank intloc; // a bank account acctaccount; int num; string nme; double bal; // read existing accounts from file vault.open("accounts.txt"); vault >> num >> nme >> bal; while (!vault.eof()) { account = account (num, nme, bal); my_bank.insert (account); vault >> num >> nme >> bal; } // display dollar values correctly cout << setiosflags(ios::fixed) << setprecision(2); rThe program assumes that a file named accounts.txt contains the data for existing accounts. rThis is the standard while loop for reading data from a file until the end of file is reached. rWe now use the insert method to add the data to the bank

Lecture Computer Science I - Martin Hardwick Bank Simulation (4) // get ready to process commands cout << "The bank is now open." ; cout << endl << endl; // loop to process user commands cout << endl << " " << endl; cout << "Enter command " << "(exit to stop): "; cin >> command; while (command != "exit") { if (command == "find") { // FIND COMMAND // get account to find cout << "Enter account num: "; cin >> goal; // search for account loc = my_bank.find(goal); rFirst case is the find command. l get account number to find from user l call Member function find to search the account list for this account

Lecture Computer Science I - Martin Hardwick Member Function Find (1) int banking::find(int goal) //PURPOSE: search for a goal account // in the list of accounts //POSTCONDITIONS: returns the // subscript of goal account or -1 if // the goal account is not found { int k;// loop variable rParameters: list of accounts, number of accounts, number of the goal account to find. rReturn: subscript of goal account if found, or –1 to indicate that it is not in the list. rSearch the list from its beginning, element by element until: l find the account l reach the end of the list rThis is called a sequential search.

Lecture Computer Science I - Martin Hardwick Member Function find (2) //search for the goal account in //the list of accounts for (k=0; k<bank.size(); k++) { if (bank[k].get_num() == goal) { return k; } // didn't find goal account return -1; } rIf the goal number is in the account list, it will be found by the for loop. l if it is found at subscript k, return k and terminate the function rIf the loop ended because k is no longer less than numaccts, then the entire list was searched and the goal account was not found. l in this case, return -1

Lecture Computer Science I - Martin Hardwick Bank Simulation (5) // display account data // or error message if (loc >= 0) { account = my_bank.get (loc) cout << "Account: " << account.get_num() << "\t" << "Owner: " << account.get_name() << "\t" << "Balance: " << account.get_balance() << endl; } else { cout << "Account " << goal <<" does not exist." << endl; } rRemember, just before this is the call to function find with the result saved in variable loc. rIf loc is greater than or equal to 0, it must be the subscript of the goal account in the account list. l in this case, display the account data. l First get the account from the bank l Call get methods to get the values

Lecture Computer Science I - Martin Hardwick Bank Simulation (6) else if (command == "list") { // LIST COMMAND cout << "List of accounts:" << endl; for (loc=0; loc<my_bank.size(); loc++) { account = my_bank.get(i); cout << "Account: " << account.get_num () << "\t" << "Owner: " << account.get_name() << "\t" << "Balance: " << account.get_balance() << endl; } rThe second case inside the while loop that processes user commands is the list command. rDisplay the account data for all accounts in the account list. rProbably better to make this a method in the banking class rCalled dump or something similar banking::dump ();

Lecture Computer Science I - Martin Hardwick Bank Simulation (7) else if (command == "insert") { // INSERT COMMAND cout << "Enter new account data:" << endl; cout << "Account number: "; cin >> account.num; cout << "Account name: "; cin >> account.name; cout << "Account balance: "; cin >> account.balance; my_bank.insert(account); } rThe third case inside the while loop that processes user commands is the insert command. l This is now a method of the banking class

Lecture Computer Science I - Martin Hardwick Function insert (1) void banking::insert (acct newacct) //PURPOSE: insert a new account into // the account list // //POSTCONDITIONS: account list // modified to add new account, // order of account list maintained { intk,j;// loop variables rParameters: new account to add to the list. rSince the list order must be maintained, we must find where in the list the new account should be placed. rOnce we know where it goes, we must make room in the list to insert the new account.

Lecture Computer Science I - Martin Hardwick Inserting Into An Order List 1.Find where the new item goes. 2.Make room for the new item. 3.Insert the new item into the list Number of elements in the list: Insert

Lecture Computer Science I - Martin Hardwick Function insert (2) // find place to put new account in list // to maintain order of list k=0; while ((k < bank.size()) && (bank[k].get_num < newacct.get_num()) ){ k = k + 1; } // add new account to list if (k == bank.size()) { // goes at end bank.push_back (newacct); } rThe loop terminates when: l we find the first account in the list with a larger account number l we reach the end of the list having found no larger account numbers rIf there are no larger account number in the list, then k equals the number of accounts at the end of the loop. l in this case, add the new account to the end of the list

Lecture Computer Science I - Martin Hardwick Function insert (3) else { // goes in middle // make room to add it bank.push_back (newacct); for (j=bank.size()-1; j>k; j--) { bank[j] = bank[j-1]; } // add it to vacated spot bank[k] = newacct; } rOtherwise, the new account belongs in element k of the list. rMove all elements from k to the end of the list, one element to the right. l it is easiest to do this in reverse order rNow we can put the new account into element k of the list without overwriting another account.

Lecture Computer Science I - Martin Hardwick Bank Simulation (8) else { // INVALID COMMAND cout << "Invalid command." << endl; } cout << endl << " " << endl; cout << "Enter a command "; << "(exit to stop): "; cin >> command; } // exit command from user cout << endl << " " << endl; cout << "The bank is now closed."; cout << endl << endl; return 0; } rThe final case in the while loop processing user commands is the default case for invalid commands. l display a suitable error message rWhen the user types the exit command, the while loop terminates. l display a message closing the bank and terminate the program l a “real” bank program would write the new account list to a file l this file would be loaded into the program the next time it runs