Lecture 1 -- 1Computer Science I - Martin Hardwick Bank Simulation (1) #include using namespace std; // Create bank account data type struct acct { //

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick Arithmetic Expressions With Integers rOperators:result is always an integer SymbolNameExampleValue (x.
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 The Programming Process rUse an editor to create a program file (source file). l contains the text of.
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 Recursion rA recursive function must have at least two parts l A part that solves a simple case of the.
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 Merge Sort Algorithm rMerge sort has two phases. l First it divides the data into smaller and smaller.
1 Lab 4 Westfield High School APCS LAB 4 Parameters, apvectors, structs.
Factorial Preparatory Exercise #include using namespace std; double fact(double); int fact(int); int main(void) { const int n=20; ofstream my_file("results.txt");
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
1 Programming Structures COMP102 Prog. Fundamentals, Structures / Slide 2 2 Structures l A Structure is a collection of related data items, possibly.
Data Structures (Second Part) Lecture 2 : Pointers Bong-Soo Sohn Assistant Professor School of Computer Science and Engineering Chung-Ang University.
Structure.
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Student Data Score First Name Last Name ID GPA DOB Phone... How to store student data in our programs? 1.
C++ Classes & Data Abstraction
Lecture Computer Science I - Martin Hardwick Making the bank object oriented rIn upcoming lectures we will be looking at efficiency issues rIn order.
Structures. An array allows us to store a collection of variables However, the variables must be of the same type to be stored in an array E.g. if we.
Classes. What is a class? Data and the functions (methods) that operate on that data – collectively called members –Example: bank account class Provide.
1 9/1/06CS150 Introduction to Computer Science 1 What Data Do We Have? CS 150 Introduction to Computer Science I.
16/19/2015 1:14 PM6/19/2015 1:14 PM6/19/2015 1:14 PMArrays and Structures Methods to manipulate a collection of values under one name. Arrays: Homogenous.
Classes. What is a class? Data and the functions (methods) that operate on that data – collectively called members –Example: bank account class Provide.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
General Computer Science for Engineers CISC 106 Lecture 26 Dr. John Cavazos Computer and Information Sciences 04/24/2009.
CS 117 Section 2 + KNET Computer accounts – ed to KNET students –Change password Homework 1 Lab Tutors –In lab for next 2 weeks –Will help you with.
CS161 Topic #15 1 Today in CS161 Lecture #15 Practicing! Writing Programs to Practice Write a game program (1 player) of Mad Math Reuse the functions to.
Structured Data Types array array union union struct struct class class.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
Programmer Defined Structures (Records)
CSCI-383 Object-Oriented Programming & Design Lecture 5.
CSCI 383 Object-Oriented Programming & Design Lecture 6 Martin van Bommel.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Basics of Most C++ Programs // Programmer: Clayton Price date: 9/4/ // File: fahr2celc.cpp 03. // Purpose:
Arrays in C++: Numeric Character (Part 2). Passing Arrays as Arguments in C++, arrays are always passed by reference (Pointer) whenever an array is passed.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
1 Strings, Classes, and Working With Class Interfaces CMPSC 122 Penn State University Prepared by Doug Hogan.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
Review for Final Exam. Contents 5 questions (20 points each) + 1 bonus question (20 points) – Basic concepts in Chapters 1-4 – Chapters 5-9 – Bonus: Chapter.
11/5/2016CS150 Introduction to Computer Science 1 Announcements  Assignment 6 due on Wednesday, December 3, 2003  Final Exam on Tuesday, December 9,
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
1. 2 Review How many bits are in a byte? a) 4 b) 8 c) 16 d) 256.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
C LANGUAGE Characteristics of C · Small size
April 11, 2005 More about Functions. 1.Is the following a function call or a function header? calcTotal(); 2.Is the following a function call or a function.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 29 Thanks for Lecture Slides:
1 11/30/05CS150 Introduction to Computer Science 1 Structs.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
13/10/2016CS150 Introduction to Computer Science 1 Multidimensional Arrays  Arrays can have more than one column  Two dimensional arrays have two columns.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
1 C++ Classes and Data Structures Course link…..
Review for Final Exam.
CS150 Introduction to Computer Science 1
Review for Final Exam.
A “User – Defined Data Type”
CS148 Introduction to Programming II
Reading from and Writing to Files Part 2
CS150 Introduction to Computer Science 1
Presentation transcript:

Lecture Computer Science I - Martin Hardwick Bank Simulation (1) #include using namespace std; // Create bank account data type struct acct { // bank account data int num; // account number string name; // owner of account float balance; // balance in account }; // Function Prototypes int find(acct bank[ ], int numaccts, int goal); void insert(acct bank[ ], int &numaccts, acct newacct); void remove(acct bank[ ], int &numaccts, int acctnum); rThis program simulates a bank by processing transactions for bank accounts. rAn array 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 we need a way to combine these three pieces of data into a single piece of account data l we will use a C++ struct to do this

Lecture Computer Science I - Martin Hardwick C++ structs rSyntax:Example: rThink of a struct as a way to combine heterogeneous data values together to form a new more complex data type. l you can use this new data type to declare variables l you can create arrays with this new data type rPlace struct definitions at the beginning of a program, after include lines and before functions and function prototypes. rTo access the components of a struct, use the dot operator. l can be used anywhere an ordinary variable can be used struct { ;... }; struct acct { int acctnum; string name; float balance; }; acctmyAccount; myAccount.acctnum = 99999; myAccount.name = Hardwick; myAccount.balance = 10000;

Lecture Computer Science I - Martin Hardwick Bank Simulation (2) 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 acct bank[1000]; // total number of accounts intnumaccts; // 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. rAssume that there will be no more than 1000 accounts. rThe existing accounts are read from a file at the start of the program. l this creates the bank array 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; // read existing accounts from file vault.open("accounts.txt"); numaccts=0; vault >> bank[0].num >> bank[0].name >> bank[0].balance; while (!vault.eof()) { numaccts = numaccts + 1; vault >> bank[numaccts].num >> bank[numaccts].name >> bank[numaccts].balance; } // 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. rNote the position of a subscript when using an array of struct types. rThis is the standard while loop for reading data from a file until the end of file is reached. rDollar values should be displayed with two digits to the right of the decimal point. l the last two lines instruct the cout object to do this when displaying float values

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 = find(bank, numaccts, goal); rUse the standard while loop to get commands from the user until the user enters the exit command. rUser commands are processed inside the loop. l since commands are strings, cant use a switch statement l therefore, use nested IF- ELSE statements rFirst case is the find command. l get account number to find from user l call function find to search the account list for this account

Lecture Computer Science I - Martin Hardwick Function Find (1) int find(acct bank[ ], int numaccts, int goal) //PURPOSE: search for a goal account // in the list of accounts //PRECONDITIONS: 0 <= numaccts, // numaccts is number of accounts // in list of accounts (i.e., bank) //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 Function find (2) //search for the goal account in //the list of accounts for (k=0; k<numaccts; k++) { if (bank[k].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) { cout << "Account: " << bank[loc].num << "\t" << "Owner: " << bank[loc].name << "\t" << "Balance: " << bank[loc].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. rOtherwise, loc must by –1 indicating that the goal account was not found. l in this case, display an error message

Lecture Computer Science I - Martin Hardwick Bank Simulation (6) else if (command == "list") { // LIST COMMAND cout << "List of accounts:" << endl; for (loc=0; loc<numaccts; loc++) { cout << "Account: " << bank[loc].num << "\t" << "Owner: " << bank[loc].name << "\t" << "Balance: " << bank[loc].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.

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; insert(bank, numaccts, account); } rThe third case inside the while loop that processes user commands is the insert command. rThis command assumes that the list of accounts is ordered by account number. rIt inserts a new account into the account list in the right place to maintain the ordering. rIt prompts the user for the data about the new account. rIf then calls function insert to add the new account to the account list.

Lecture Computer Science I - Martin Hardwick Function insert (1) void insert(acct bank[ ], int &numaccts, acct newacct) //PURPOSE: insert a new account into // the account list //PRECONDITIONS: 0 <= numaccts, // numaccts is number of accounts // in account list, newacct is a new // account to be added, account // list is in order by account num //POSTCONDITIONS: account list // modified to add new account, // order of account list maintained { intk,j;// loop variables rParameters: list of accounts, number of accounts, new account to add to the list. rBoth the account list (i.e., bank) and the number of accounts (i.e., numaccts) will change. l numaccts must be passed by reference l arrays are always passed by reference 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 ((bank[k].num < newacct.num) && (k < numaccts)) { k = k + 1; } // add new account to list if (k == numaccts) { // goes at end bank[numaccts] = newacct; numaccts = numaccts + 1; } 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 for (j=numaccts; j>k; j--) { bank[j] = bank[j-1]; } // add it to vacated spot bank[k] = newacct; numaccts = numaccts + 1; } 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. rVariable numaccts must be incremented since a new account has been added to the list.

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