Introduction to Computer Science
Download
Report
Transcript Introduction to Computer Science
Introduction to Computer Science
COMP 51 – Fall 2012 – Section 2
Structures
2
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)
3
Structures
4
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
5
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…
6
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
7
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
struct CDAccount
{
double balance;
double interestRate;
int term;
};
8
Declare Structure Variable
Step 1: Define structure 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;
9
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
account.balance
account.interestRate
account.term
A period!
“dot”
10
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!
11
Example Program
#include <iostream>
using namespace std;
// Structure for certificate of deposit
struct CDAccount
{
double balance;
double interestRate;
int term;
};
Function returning a struct
Function taking a struct
CDAccount openAccount(void);
void printAccount(CDAccount account);
12
Example Program
int main(void)
{
CDAccount account;
account = openAccount();
printAccount(account);
return 0;
}
Declare a new instance of the
CDAccount structure called “account”
13
Example Program
CDAccount openAccount(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)
14
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;
15
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
16
Pitfall – Required Semicolon!
Semicolon after structure definition is required!
struct WeatherData
{
double temperature;
double windVelocity;
}; semicolon!
Required since you can declare structure
variables in this location
17
Pitfall – Initialization
Member variables cannot be initialized in the
declaration
The structure definition only defines the types,
names and order of members
struct WeatherData
{
double temperature = 32.0;
double windVelocity = 10;
};
This is not allowed
18
Uniqueness of Names
Different structures may use the same member
variables names without confusion
struct CDAccount
{
double balance;
double interestRate;
int term;
};
struct CheckingAccount
{
double balance;
double interestRate;
};
Names within a structure still have to be unique,
however
19
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 account1
account2 = account1;
Simply copies each member variable from apples
into member variables from oranges
Can’t do anything else, however
No comparisons (==, >, <, etc.)
At least not without extra programming work…
20
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
21
Lab 8: Structures Exercise
22
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.
23
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[], int teamSize);
Create a function to print out the name, weapon and
highest score of each fencer on the team.
printTeam(Fencer team[], int teamSize);
24
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[], int teamSize);
Call these three functions in sequence inside
main().
25
Lab 8
Sample input and output
26
Questions?
?