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.

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick Making our programs more flexible rSo far we have largely programmed using l Arrays of integers l Arrays.
Advertisements

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 Making the bank object oriented rIn upcoming lectures we will be looking at efficiency issues rIn order.
Chapter 7: User-Defined Functions II
1 Chapter Structured Types, Data Abstraction and Classes Dale/Weems.
True or false A variable of type char can hold the value 301. ( F )
1 Lecture 6 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Computer Science 1620 Variables and Memory. Review Examples: write a program that calculates and displays the average of the numbers 45, 69, and 106.
Chapter 6 Control Structures.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Program Input and the Software Design Process ROBERT REAVES.
CSCI 1730 January 17 th, 2012 © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 Chapter 9 Scope, Lifetime, and More on Functions.
Pointers CS362. Pointers A Pointer is a variable that can hold a memory address Pointers can be used to: Indirectly reference existing variables (sometimes.
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)
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 10: Records (structs)
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 CS161 Introduction to Computer Science Topic #3.
1 Chapter 11 Structured Types, Data Abstraction and Classes Dale/Weems/Headington.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
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.
Structures (aka records, structs) Textbook Chapter 11 sections:
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
1 Simple File I/O Chapter 11 Switch Statement Chapter 12.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
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.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
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.
1 Chapter 9 Scope, Lifetime, and More on Functions.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 29 Thanks for Lecture Slides:
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
CS1201: Programming Language 2 Function I By: Nouf Aljaffan Edited by : Nouf Almunyif.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Chapter Structured Data 11. Combining Data into Structures 11.2.
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 Chapter 10 & 11 enum & Structured Types Dale/Weems.
1 C++ Classes and Data Structures Course link…..
C++ Basic Input and Output (I/O)
What Actions Do We Have Part 1
Basic Elements of C++.
Objectives Identify the built-in data types in C++
Basic Elements of C++ Chapter 2.
Chapter 9 Scope, Lifetime, and More on Functions
Review for Final Exam.
Review for Final Exam.
Fundamental Programming
Reading from and Writing to Files
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Reading from and Writing to Files Part 2
Reading from and Writing to Files
Presentation transcript:

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 to form a new more complex data type. n you can use this new data type to declare variables n you can create vectors with this new data type l Place struct definitions at the beginning of a program, after include lines and before functions and function prototypes. l To access the components of a struct, use the dot operator. n 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 = “Nate”; myAccount.balance = 10000;

3 struct acct // Create bank account data type struct acct { // does not allocate memory int num; string name; floatbalance; }; int main() { … acct thisAcct ; // declare variables of acct acct anotherAcct ;

4 thisAcct 5000.num name “Sylvester”.balance num name “Tweedy”.balance anotherAcct

5 struct type declarations If the struct type declaration precedes all functions it will be visible throughout the rest of the file. If it is placed within a function, only that function can use it. It is common to place struct type declarations with TypeNames in a (.h) header file and #include that file.

6 Use the dot to access struct members acct thisAcct;// declare variable for an account thisAcct.balance += 100; thisAcct.num = ; cin >> thisAcct.balance; getline ( cin, thisAcct.name ); thisAcct.name[ 0 ] = toupper (thisAcct.name[ 0 ] ) ;

7 struct Operations l I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED! l operations valid on an entire struct type variable: assignment to another struct variable of same type, pass to a function as argument (by value or by reference), return as value of a function

8 Examples of legal struct operations anotherAccount = thisAcount ; // assignment writeOut(thisAccount, cout); // value parameter deposit(thisAccount, 100); // reference parameter thisAccount = getAccountData( ); // return value of // function NOW WE’LL WRITE THE 3 FUNCTIONS USED HERE...

9 void writeOut(acct thisAcct, ostream & out) // Prints out values of all members of thisAcct // Precondition: all members of thisAcct are assigned // Postcondition: all members have been written out { out << “Account # ” << thisAcct.num << thisAcct.name << endl ; out << “Name: ” << thisAcct.name << endl ; out << “Balance $” << setprecision(2) << thisAcct.balance << endl ; } * Note that the struct acct is not passed by reference because we do not want to change it in the function. Also note the second paramenter is of type ostream (which allows us to call it with a filename OR cout). 9

10 void deposit ( /* inout */ acct & thisAcct, float amount) // Adds amount to balance // Precondition: thisAccount.balance is assigned // Postcondition: thisAcct.balance = + amount { thisAcct.balance += amount ; } Passing a struct Type by Reference

11 acct getAccountData ( ) // Obtains all information about an account from keyboard // Postcondition: // Function value == acct members entered at kbd { acct thisAcct ; char response ; do {// have user enter all members until they are correct. } while (response != ‘Y’ ) ; return thisAcct ; } 11

12 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 floatbalance; // balance in account }; // Function Prototypes int find(vector bank, int goal); void writeOut(acct a, ostream & out); acct getAccountData(); l This program simulates a bank by processing transactions for bank accounts. l A vector is used to hold the list of bank accounts. l A bank account consists of an account number, the name of the person who owns it, and the current balance. n we need a way to combine these three pieces of data into a single piece of account data n we will use a C++ struct to do this

13 Bank Simulation (2) int main () { // list of bank accounts vector bank; // total number of accounts intnumaccts; // file with list of bank accounts ifstream vault (“accounts.txt”); // user request stringcommand; // account number to find intgoal; l The main function creates the list of bank accounts and processes user commands to perform transactions. l We want the vector to be a list of variable length n we do not know how many bank accouts the file has l The existing accounts are read from a file at the start of the program. n add each to the bank vector l User commands are typed as strings (e.g., find, insert, exit).

14 Bank Simulation (3) // subscript of account in bank intloc; // a bank account acctaccount; // read existing accounts from file vault.open("accounts.txt"); vault >> account.num >> account.name >> account.balance; while (vault) { bank.push_back(account); vault >> account.num >> account.name >> account.balance; } // display dollar values correctly cout << fixed << setprecision(2); l The program assumes that a file named accounts.txt contains the data for existing accounts. l This is the while loop for reading data until the end of file. l Dollar values should be displayed with two digits to the right of the decimal point. n the last two lines instruct the cout object to do this when displaying float values

15 Bank Simulation (4) // loop to process user commands cout << "Enter command " << "(exit to stop): "; cin >> command; while (command != “exit”) { if (command == "find") { // get account to find cout << "Enter account num: "; cin >> goal; // search for account loc = find(bank, goal); if (loc >= 0) writeOut(bank[loc]); else { cout << "Account " << goal <<" does not exist." <<endl; } l Use the standard while loop to get commands from the user until the user enters the exit command. l User commands are processed inside the loop. n since commands are strings, can’t use a switch statement n therefore, use nested IF- ELSE statements l First case is the find command. n get account number to find from user n call function find to search the account list for this account n Find returns -1 if not found

16 Function Find int find(vector bank, int goal) { int k;// loop variable // search for the goal account in // the list of accounts for (k=0; k<bank.size(); k++) { if (bank[k].num == goal) return k; } // didn't find goal account return -1; } l Parameters: list of accounts, number of the goal account to find. l Return: subscript of goal account if found, or –1 to indicate that it is not in the list. l Search the list from its beginning, element by element until: n find the account n reach the end of the list l This is called a sequential search.

17 Bank Simulation (5) else if (command == "list") { // LIST COMMAND cout << "List of accounts:" << endl; for (loc=0; loc<bank.size(); loc++) { writeOut(bank[loc], cout); cout << endl; } l The second case inside the while loop that processes user commands is the list command. l Display the account data for all accounts in the account list.

18 Bank Simulation (6) else if (command == "insert") { acct newacct = getAccountData(); bank.push_back(newacct); } l The third case inside the while loop that processes user commands is the insert command. l In this case we call the getAccountData function to prompt the user for data. This function returns an acct. l We push that acct onto the end of the bank

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

20 C++ Data Type class l Classes are very similar to structs, as they group related data together, and allow programmers to use “member functions” that manipulate that data. l 2 kinds of class members: data members and function members l You will learn much more about classes in CS 2.