Upload
linda-garrett
View
219
Download
2
Embed Size (px)
Citation preview
1
Today’s ObjectivesToday’s Objectives
Announcements• Quiz #1 on 8-Jun (Wednesday) – over C++ material in Ch. 1, 2, 3
Be sure to study math operators, assignment operators, relational operators, logic operators, if statements, for loops, while loops, incrementing, and common errors
Quick review of some basic C++ (Ch. 1 and Ch. 2)• C++ style output and input• Escape sequences• Variables• Arithmetic operators, equality operators, and relational operators
Control structures (Ch. 4 and Ch. 5)• Control structures – if and else, while, for, switch• Stream manipulators• Assignment operators and logical operators• Increment and decrement operators
Intro to UML – Unified Modeling Language• Algorithms and pseudocode• UML diagrams• The Software Life Cycle
Bonus Lab
5-Jun-20065-Jun-2006
2
Quick Review ofSome Basic C++Quick Review ofSome Basic C++
Some C++ Features in Chapters 1 and 2
3
Simple Example from Last WeekSimple Example from Last Week
Page 42, Fig. 2.4 Comments
// Everything after it on the same line is a comment/* Everything in between is a comment */
int main(){} //All execution starts here C++ statements end with semicolons ; Preprocessor directive to include a C++ standard library
#include <iostream>
All C++ library elements are in the “std” namespaceusing namespace std;using std::cout;
Outputcout represents the standard output, usually the screen<< stream insertion operator, can be concatenatedcerr represents the standard error output, also usually the screen
Quick Review (Deitel)Quick Review (Deitel)
4
Escape SequencesEscape Sequences
Page 40, Fig. 2.2
Special characters used in printing\n Newline
\t Tab
\\ Backslash
\" Double quote
Example:
cout << "\nEscape sequences begin with a \"\\\"\n";
Quick Review (Deitel)Quick Review (Deitel)
5
VariablesVariables
Declaring variables, page 1232, Append. C//Datatype followed by a variable name//Can also be initialized when declaredint n, m = 0; //Initializes m but not ndouble x = 0.0;bool done = false;char userSelection = 'X';int n(0); //Functional style of initialization
What will print? Do variables have to be initialized?#include <iostream>using namespace std;int main(){
int n;cout << "n = " << n << "\n";
}
Quick Review (Deitel)Quick Review (Deitel)
6
Second Example from Last WeekSecond Example from Last Week
Page 43, Fig. 2.5
Inputcin represents the standard input, usually the keyboard>> stream extraction operator
cin can be used to capture input from the keyboard up to the first whitespace (e.g., space or return)double quiz1;cout << "Enter your grade for Quiz 1: ";cin >> quiz1;cout << "You typed " << quiz1 << endl;
endl to output a newline and flush output buffer
Quick Review (Deitel)Quick Review (Deitel)
7
Arithmetic OperatorsArithmetic Operators
Arithmetic operators, page 48, fig. 2.9+ Addition- Subtraction* Multiplication/ Division% Modulus, result is the remainder
Integer divisionint a = 28, b = 5;cout << "a / b = " << (a / b) << endl; //What prints?cout << "a % b = " << (a % b) << endl; //What prints?
Precedence, page 49, fig. 2.10 and page 1228, Append. A• Parentheses, innermost first, then left to right• *, /, %, left to right• +, -, left to right• Example: cout << (2 * (5 * 5) + 3 * 5) + 7 << endl;
Quick Review (Deitel)Quick Review (Deitel)
8
Equality Operators andRelational Operators
Equality Operators andRelational Operators
Equality operators• equality operator == (don’t confuse with = )
x == y; //x is equal to y• operator !=
x != y; //x is not equal to y
Relational operators• operator <
x < y; //x is less than y• operator >
x > y; //x is greater than y• operator <=
x <= y; //x is less than or equal to y• operator >=
x >= y; //x is greater than or equal to y
Quick Review (Deitel, 51–54, Fig. 2.12)Quick Review (Deitel, 51–54, Fig. 2.12)
9
Where’s the Error?Where’s the Error?
#include <iostream>using namespace std;int main(){ bool done = false; while( !done ){ cout << "Continue?(Y/N): "; char input = 'Y'; cin >> input; if( input = 'N' )
done = true; } cout << "Bye!\n";}
Quick Review (Deitel)Quick Review (Deitel)
10
Control StructuresControl Structures
C++ Features in Chapters 4 and 5
11
C++ Control StructuresC++ Control Structures
Sequence – built-in Selection structures
• if• if/else• switch
Repetition structures• while• do/while• for
Control Structures (Deitel, 127–131)Control Structures (Deitel, 127–131)
12
if/elseif/else
Used to select from different actions, based on whether a condition is true
if( courseScore >= 92.5 )courseGrade = "A";
else if( courseScore >= 89.5 )courseGrade = "A-";
elsecourseGrade = "B";
Control Structures (Deitel, 131–137)Control Structures (Deitel, 131–137)
13
Where’s the Error?Where’s the Error?
if( courseScore >= 92.5 );
courseGrade = "A";
Control Structures (Deitel)Control Structures (Deitel)
14
Counter-Controlled while LoopCounter-Controlled while Loop
A while loop repeats an action as long as a condition is true
In this example, a counter controls the number of iterations
int grade, total=0, gradeCounter=1;while( gradeCounter <= 10 ){cout << "Enter grade ";cin >> grade;total = total + grade;gradeCounter = gradeCounter + 1;
}
Control Structures (Deitel, 137–145, Fig. 4.9 on p. 142)Control Structures (Deitel, 137–145, Fig. 4.9 on p. 142)
15
Where’s the Error?Where’s the Error?
int grade, total=0, gradeCounter=1;while( gradeCounter <= 10 );{cout << "Enter grade ";cin >> grade;total = total + grade;gradeCounter = gradeCounter + 1;
}
Control Structures (Deitel)Control Structures (Deitel)
16
Sentinel-Controlled while LoopSentinel-Controlled while Loop
A sentinel is a special value used to signal that looping should end – useful when the number of iterations is not known in advance
int main(){char selection;string input;bool done = false;while( !done ){
printMenu();cout << "Enter your selection (x to quit): ";cin >> input;selection = input[0];if( selection == 'x' )
done = true;}
}
Control Structures (Deitel, 145–153, Fig. 4.13 on p. 151)Control Structures (Deitel, 145–153, Fig. 4.13 on p. 151)
17
Stream ManipulatorsStream Manipulators
Special elements that can be used to format output Can be used with the stream insertion operator << Include the following library: #include <iomanip>
//Fig. 4.13, page 151, line 86cout << "Average = " << setprecision(2) << fixed << average << endl;
• setprecision(2) – print two digits to the right of the decimal• fixed – always use fixed point notation, not scientific notation, and
always print any trailing zeroes• setw(16) – set the width for each field to 16 spaces• left – left-justify a field
Control Structures (Deitel, 155)Control Structures (Deitel, 155)
18
Assignment OperatorsAssignment Operators
Operators for abbreviating assignment expressions
Examplesint a = 1, b = 1, c = 1;a += 2; //The same as: a = a + 2a += b; //a = a + bb -= 3; //b = b – 3c *= 4; //c = c * 4c *= c;
//What will be printed?cout << "c = " << c << endl;
Control Structures (Deitel, 161, Fig. 4.19)Control Structures (Deitel, 161, Fig. 4.19)
19
Increment and Decrement OperatorsIncrement and Decrement Operators
Operators that add 1 or subtract 1 from a variable
Post-increment and post-decrementint a = 1, b = 1;a++; // a = a + 1b--; // b = b – 1
Pre-increment and pre-decrement++a; // a = a + 1--b; // b = b - 1
Control Structures (Deitel, 161–164, Fig. 4.20)Control Structures (Deitel, 161–164, Fig. 4.20)
20
for Loopfor Loop
for( int i=0; i<10; ++i ){ cout << i << " ";}
Initialization – assigns the starting value and is executed once.
Condition – tested at the beginning of each loop, and the loop is executed only if it evaluates to true.
Expression – evaluated at the end of each loop
Block of statements executed in
the loop
Control Structures (Deitel, 188–197)Control Structures (Deitel, 188–197)
21
A block is needed only if multiple statements are executed in each loop.
for( int i=0; i<10; ++i ){ cout << i; cout << " ";}
for Loopfor Loop
If only one statement is executed in each loop, it’s not necessary to define a
block with { and }.
for( int i=0; i<10; ++i ) cout << i << " ";
Control Structures (Deitel, 188–197)Control Structures (Deitel, 188–197)
22
Changes to the Value of iChanges to the Value of i
for( int i=0; i<5; ++i ){ cout << i << " ";}
IterationValue of i
during the loopExpression at the end of the loop
First loop 0 (starting value) i = i + 1
Second loop 1 i = i + 1
Third loop 2 i = i + 1
Fourth loop 3 i = i + 1
Fifth loop 4 i = i + 1
Control Structures (Deitel, 188–197)Control Structures (Deitel, 188–197)
23
for Loop Guidelinefor Loop Guideline
Use a “for” loop when you already know how many times to repeat your code
for loops are usually used to step through a data structure with a known length, such as an array
const int SIZE = 5;int myArray[SIZE] = {0,0,0,0,0};for( int i=0; i<SIZE; ++i ) cout << myArray[i] << " ";
Control Structures (Deitel, 188–197)Control Structures (Deitel, 188–197)
24
Nested for LoopNested for Loop
int result = 0;for( int i=0; i<3; ++i ) for( int j=0; j<5; ++j ) result++;
i j result
0 0 1
0 1 2
0 2 3
0 3 4
0 4 5
1 0 6
1 1 7
1 2 8
1 3 9
1 4 10
2 0 11
2 1 12
2 2 13
2 3 14
2 4 15
Control Structures (Deitel, 188–197)Control Structures (Deitel, 188–197)
25
Nested Loop with Dependent VariableNested Loop with Dependent Variable
int result = 0;for( int i=0; i<3; ++i ) for( int j=i; j<5; ++j ) result++;
i j result
0 0 1
0 1 2
0 2 3
0 3 4
0 4 5
1 1 6
1 2 7
1 3 8
1 4 9
2 2 10
2 3 11
2 4 12
Control Structures (Deitel, 188–197)Control Structures (Deitel, 188–197)
26
How many iterations?How many iterations?
for( int i=0; i<10; ++i ) cout << i << " ";
for( int i=10; i>0; --i ) cout << i << " ";
int result = 0;for( int i=0; i<2; ++i ) for( int j=0; j<3; ++j ) result++;
Control Structures (Deitel, 188–197)Control Structures (Deitel, 188–197)
27
switch Structureswitch Structure
Can replace a complicated if/else structure
char selection;cin >> selection;switch( selection ){ case '1': myStore.viewCustomerList(); break; case 'x': case 'X': done = true; break; default: cout << "Incorrect input" << endl; break;}
Control Structures (Deitel, 199–205)Control Structures (Deitel, 199–205)
This controlling expression is compared to each of the case labels
Execution continues at the case label that matches
The break causes execution to go to the next line following the switch
28
Logical OperatorsLogical Operators
Logical AND – both conditions must be true&&
Logical OR – one or the other condition must be true||
Examples:
if( gender == 'F' && age > 64 )
seniorFemales++;
if( average >= 90 || finalExam >= 90 )
grade = 'A';
Control Structures (Deitel, 211–215)Control Structures (Deitel, 211–215)
29
Intro to UMLIntro to UML
A tool forobject-oriented analysis and design
30
Software ProcessSoftware Process
Series of steps for software development Sometimes called a “method”
No standard software process• But it is important to use a process
Important for non-trivial programs
Advantages1. Repeatable procedure2. Remember all the things that need to be done3. Measurable progress
Intro to UML (Sommerville)Intro to UML (Sommerville)
31
Steps in Software DevelopmentSteps in Software Development
Also known as the “Software Life Cycle”
Requirements gathering Analysis Program Design Coding Testing Operations
Intro to UML (Royce)Intro to UML (Royce)
32
Analysis and DesignAnalysis and Design
Analysis • Determine what a program should do, but not how it should
do it• Build models, e.g. with UML or pseudocode algorithms
Program Design• Adjust the models to simplify implementation and improve
execution• Determine how the program should work
When it’s done with object-oriented programs, it’s called object-oriented analysis and design, or OOAD
Intro to UML (Royce)Intro to UML (Royce)
33
Tools for Analysis and DesignTools for Analysis and Design
Pseudocode algorithms• Algorithm = A step-by-step procedure for performing a
task in a finite time• Pseudocode = structured, English-like statements that
describe the algorithm
UML• Unified Modeling Language• Graphical language used to model object-oriented
programs• Use case diagrams, class diagrams, sequence
diagrams, activity diagrams, etc.
Intro to UML (Deitel)Intro to UML (Deitel)
34
Algorithm arrayMax(A,n):Input: An array A storing n >= 1 integers.Output: The maximum element in A.
currentMax = A[0]for i = 1 to n – 1 do if currentMax < A[i] then currentMax = A[i]return currentMax
Pseudocode example 1 (more code-like)
Pseudocode AlgorithmPseudocode AlgorithmIntro to UML (Deitel, 125–127; Goodrich)Intro to UML (Deitel, 125–127; Goodrich)
set currentMax to the first element in the input arrayfor each element in the array if currentMax < the new element then set currentMax to the new elementreturn currentMax
Pseudocode example 2 (more English-like)
35
UMLUML
Graphical language – symbols used to create diagrams that model object-oriented programs
Intro to UML (Deitel)Intro to UML (Deitel)
Use casediagrams
Classdiagrams
Sequence diagrams
36
Phase 1: Requirements GatheringPhase 1: Requirements Gathering
What are we making?• Consult the stakeholders• Read the assignment and ask the instructor
Goal• Problem statement• List of requirements
UML tool• Use case diagrams
Intro to UML (Eckel)Intro to UML (Eckel)
37
Phase 2: Analysis and DesignPhase 2: Analysis and Design
How will we build it?• Come up with a design describing the classes
Goal• Object model• Functional model – describes the operations of
the objects
Tools• UML – class diagrams• Pseudocode for the functional model
Intro to UML (Eckel; Blaha)Intro to UML (Eckel; Blaha)
38
Phase 3: Coding and TestingPhase 3: Coding and Testing
Build the first version• Start programming
Goal• Get something working• Keep it simple – small, simple classes
Testing• Create tests early – even before coding• Automate testing as much as possible so that
tests can be run every time the program changes
Intro to UML (Eckel)Intro to UML (Eckel)
39
IterationsIterations
Iteration = repetition You won’t get the whole project right the
first time Start with the core functionality – get it
working, then add more features with each iteration
Intro to UML (Eckel)Intro to UML (Eckel)
40
Case Study: Video Rental SystemPhase 1 – What are we making?
Case Study: Video Rental SystemPhase 1 – What are we making?
1. The store will rent movies as either VHS tapes or DVDs.
2. The store will also rent games.
3. Multiple copies of all the most popular movies will be stocked.
4. The store clerk will need to be able to look up a movie by its title in order to determine whether it’s available in the store.
5. The store owner will need to print a list of movie and game titles that are in stock when doing the inventory.
6. The store needs to keep track of its customers, and only the registered customers can rent items. The clerk must be able to determine which customer has checked out an item, and also how many items they have checked out.
7. After renting a movie or game, the customer must return it after three days.
Intro to UMLIntro to UML
41
Phase 2 – How will we build it?Discover classes by finding the nouns
Phase 2 – How will we build it?Discover classes by finding the nouns
1. The store will rent movies as either VHS tapes or DVDs.
2. The store will also rent games.
3. Multiple copies of all the most popular movies will be stocked.
4. The store clerk will need to be able to look up a movie by its title in order to determine whether it’s available in the store.
5. The store owner will need to print a list of movie and game titles that are in stock when doing the inventory.
6. The store needs to keep track of its customers, and only the registered customers can rent items. The clerk must be able to determine which customer has checked out an item, and also how many items they have checked out.
7. After renting a movie or game, the customer must return it after three days.
Intro to UMLIntro to UML
42
Eliminate nouns that are: irrelevant, redundant, or used only as values
Eliminate nouns that are: irrelevant, redundant, or used only as values
1. The store will rent movies as either VHS tapes or DVDs.
2. The store will also rent games.
3. Multiple copies of all the most popular movies will be stocked.
4. The store clerk will need to be able to look up a movie by its title in order to determine whether it’s available in the store.
5. The store owner will need to print a list of movie and game titles that are in stock when doing the inventory.
6. The store needs to keep track of its customers, and only the registered customers can rent items. The clerk must be able to determine which customer has checked out an item, and also how many items they have checked out.
7. After renting a movie or game, the customer must return it after three days.
Intro to UMLIntro to UML
43
Remaining nouns establish the basic structure of the object model
Remaining nouns establish the basic structure of the object model
storemovie
VHS tape
DVD
game
list
customer
item
Intro to UMLIntro to UML
In UML, Classes are modeled as rectangles, which can be divided into three sections.
The class name is at the top. The data members are in the middle. Member functions are at the bottom.
RentalItem– title : string– copiesInStock : int– copiesAvailable : int
44
Operations can be discoveredby creating use cases
Operations can be discoveredby creating use cases
1. The store will rent movies as either VHS tapes or DVDs.
2. The store will also rent games.
3. Multiple copies of all the most popular movies will be stocked.
4. The store clerk will need to be able to look up a movie by its title in order to determine whether it’s available in the store.
5. The store owner will need to print a list of movie and game titles that are in stock when doing the inventory.
6. The store needs to keep track of its customers, and only the registered customers can rent items. The clerk must be able to determine which customer has checked out an item, and also how many items they have checked out.
7. After renting a movie or game, the customer must return it after three days.
Intro to UMLIntro to UML
45
Consider how a user of the system will interact with it
Consider how a user of the system will interact with it
1. The store will rent movies as either VHS tapes or DVDs.
2. The store will also rent games.
Intro to UMLIntro to UML
StoreEmployee
Check out itemto customer
3. Multiple copies of all the most popular movies will be stocked.
StoreEmployee
Add an item
46
Validate the use case diagram with the stakeholders
Validate the use case diagram with the stakeholders
Intro to UMLIntro to UML
StoreEmployee Check out item
to customer
Add an item
Check in itemfrom customer
View itemsby title
Search fora title
Search fora customerAdd a customer
47
Express the use cases as algorithms describing the operations
Express the use cases as algorithms describing the operations
Algorithm checkOutItem( title )
for each item in inventory
if( item.title == title )
item.checkOut()
Intro to UMLIntro to UML
StoreEmployee
Check out itemto customer
RentalItem– title : string– copiesInStock : int– copiesAvailable : int
+ checkOut()
Store
+ checkOutItem()
Then add the operations to the appropriate class.
48
Bonus Lab #1Bonus Lab #1
Optional Procedure
• First, a demo by the instructor• Then you will complete the assignment on your own• Print it and hand it in before the end of class
Rules• Do your own work, but you may help each other• You may ask the instructor for help• You may leave if you finish early or if you do not wish to do this
assignment
1 bonus point added to a quiz grade for each correctly completed lab handed in before the end of class
49
ReferencesReferences
Blaha, M., Premerlani W., Object-Oriented Modeling and Design for Database Applications. Upper Saddle River, NJ: Prentice Hall, 1998.
Deitel, H. M., and P. J. Deitel, C++ How to Program, Fourth Edition. Upper Saddle River, NJ: Prentice Hall, 2003.
Eckel, B., Thinking in C++, Second Edition. Upper Saddle River, NJ: Prentice Hall, 2002.
Goodrich, M. T., R. Tamassia, and D. Mount, Data Structures and Algorithms in C++. Hoboken, NJ: John Wiley & Sons, Inc., 2004.
Josuttis, Nicolai M., The C++ Standard Library, A Tutorial and Reference. Boston: Addison-Wesley, 1999.
Royce, W., Software Project Management. Boston: Addison-Wesley, 1998.
Sommerville, I. ,Software Engineering. Harlow, England: Addison-Wesley, 2001.