260 likes | 381 Views
Introduction to Computer Science. COMP 51 – Fall 2012 – Section 2. Structures. Business. Exam 2 next week (Review on Wed) Office hours will be next Thurs instead of Tues Project 5 – Part A Will discuss briefly on Monday Due Monday, Nov 26 th
E N D
Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures
Business • Exam 2 next week (Review on Wed) • Office hours will be next Thurs instead of Tues • Project 5 – Part A • Will discuss briefly on Monday • Due Monday, Nov 26th • Also on Monday, you will complete Lab 8 (which we will start today). I will be in class until noon (at which time I have to leave for a meeting)
Structures • Prior knowledge – Arrays • Collection of multiple values of the same type • New concept – Structures • Collection of multiple values of different types • Treated as a single item, like arrays • Several key differences • Structure elements are accessed by name, not by index number • Must first define structure prior to declaring any variables
Why Structures? • The pieces of data are related in some way • Easier to keep them together (all in one place) • Easier to move them around all at once! • Examples • Certificate of Deposit at a bank • Account balance, interest rate, term length • Time of day • Hour, minute, second • Student information record • First name, last name, student ID number, cell phone, home phone, campus phone, etc…
New Keyword: struct • The keyword struct is used to create a new structure • Each item (member) inside the structure has a name, just like a variable • Two (or more) names to keep track of now • The name of the structure type • The name(s) of elements inside the structure
Define Structure Type • Define struct globally (typically) • Example for certificate of deposit account • Name of structure? • CDAccount • Name of members in the structure? • balance, InterestRate, term structCDAccount{ double balance; double interestRate;intterm;};
Declare Structure Variable • Step 1: Definestructure type (previous slide) • Compiler then knows what a “CDAccount” is • Step 2: Declare a variable with this new structure type • Just like declaring an int, float, char, … • Variable account of type CDAccount • It contains “member variables” CDAccount account;
Accessing Structure Members • Individual elements are called “member variables” • Different structure types can have same member variable names without conflict • New operator to access members: . • Use to read or write a member variable A period! “dot” account.balance account.interestRate account.term
Structures as Function Arguments • Passed like any simple data type • Pass-by-value or Pass-by-reference • Neat trick: Easily pass multiple data items to a function! • Can also be returned by function • Return type is structure type • Neat trick: Easily return multiple data items from a function!
Example Program #include <iostream> using namespace std; // Structure for certificate of deposit structCDAccount { double balance; double interestRate; int term; }; CDAccountopenAccount(void); void printAccount(CDAccount account); Function returning a struct Function taking a struct
Example Program intmain(void) { CDAccount account; account = openAccount(); printAccount(account); return 0; } Declare a new instance of the CDAccount structure called “account”
Example Program CDAccountopenAccount(void) { CDAccount account; cout << "Enter account balance: $"; cin >> account.balance; cout << "Enter account interest rate in %: "; cin >> account.interestRate; cout << "Enter number of months until maturity: "; cin >> account.term; return account; } Returns the variable account, which is a structure of type CDAccount and contains 3 member variables (balance, interestRate, and term)
Example Program void printAccount(CDAccount account) { double rateFraction, interestEarned, endBalance; rateFraction = account.interestRate/100.0; interestEarned = account.balance* (rateFraction*(account.term/12.0)); endBalance = interestEarned + account.balance; cout << "When your CD matures in " << account.term << " months, it will have a balance of $" << endBalance << endl; }
Example Output Enter account balance: $100.00 Enter account interest rate in %: 10.0 Enter number of months until maturity: 6 When your CD matures in 6 months, it will have a balance of $105
Pitfall – Required Semicolon! • Semicolon after structure definition is required! • structWeatherData{ double temperature; double windVelocity;}; semicolon! • Required since you can declare structurevariables in this location
Pitfall – Initialization • Member variables cannot be initialized in the declaration • The structure definition only defines the types, names and order of members • structWeatherData{ double temperature = 32.0; double windVelocity = 10;}; This is not allowed
Uniqueness of Names • Different structures may use the same member variables names without confusion • Names within a structure still have to be unique, however structCDAccount{ double balance; double interestRate;int term;}; structCheckingAccount{ double balance; double interestRate;};
Structure Assignments • An entire structure can be copied in a single statement (in contrast to arrays, which must be element by element) • Declare two structure variables • CDAccount account1;CDAccount account2;// Set data in account1account2 = account1; • Simply copies each member variable from applesinto member variables from oranges • Can’t do anything else, however • No comparisons (==, >, <, etc.) • At least not without extra programming work…
Arrays of Structures • An array of 10,000 CD account structures • CDAccount accounts[10000]; • Accessing an element of the structure in the array • cout << “Account #10 balance is $” << accounts[10].balance << endl; • Structures can have elements that are arrays, too
Lab 8 • You’re going to create a program to store information about a team of fencers at a tournament. • Create a Fencer structure to store the first name, weapon and scores from 2 bouts for each fencer. There are three possible weapons: “foil”, “epee” and “saber”. The scores for a bout are integers between 0 and 15.
Lab 8 • Create an array of 5 Fencers. This array should be declared in main(). You will pass it to functions that use it. (Remember that arrays are always passed by reference to functions). • Create a function to prompt the user for information about each fencer and fill it into the array • getTeam(Fencer team[], intteamSize); • Create a function to print out the name, weapon and highest score of each fencer on the team. • printTeam(Fencer team[], intteamSize);
Lab 8 • Create a function to ask the user to select a weapon and then print out the names of all the fencers who use that particular weapon. • weaponChoice(Fencer team[], intteamSize); • Call these three functions in sequence inside main().
Lab 8 Sample input and output
Questions? ? ? ?