Upload
lamtram
View
215
Download
0
Embed Size (px)
Citation preview
137
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
CSC-201 - Computer Science ILecture 5 Chapter 7
Dr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck CartledgeDr Chuck Cartledge
September 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910amSeptember 21 2016 at 910am
237
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Table of contents I
1 Test Results
2 Schedule
3 Miscellanea
4 Control Structs
5 Addrsquol Operrsquos
6 Break
7 Hands on
8 Q amp A
9 Conclusion
10 References
11 Files
337
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Histograms
Histogram of questions and misses
437
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Histograms
Histogram of letter grades
Test scores are only part of your final grade See syllabus
537
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Histograms
Q amp A time
ldquorsquoThe Answer to the GreatQuestion Of Life the Universeand Everything is forty-tworsquo said DeepThought with infinite majestyand calmrdquoDouglas Adams TheHitchhikerrsquos Guide to theGalaxy
637
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Schedule for the semester
Wk Date Topic Wk Date Topic1 0822 Chaps 1 ndash 2 X 9 1017 Chap 102 0829 Chaps 3 ndash 4 X 10 1024 Chaps 10 ndash 113 0905 Chap 5 X 11 1031 Chaps 10 ndash 114 0912 Test ndash Chap 6 X 12 1107 Testndash Chap 145 0919 Chap 7 13 1114 Chap 146 0926 Chap 8 14 1128 Chap 187 1003 Chap 9 15 1205 Chap 188 1010 Test ndash Chap 10 16 1212 Exam
737
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Programming assignment 003
File Based Address Book
Objectives are fairly straightforward
Accept commands from the user
Read strings from a data file
Search strings for data from user
Output strings to the screen in aparticular format or outputmessage
Submit your source code
This is a single person effort (not ateam effort)
Due by start of class 4 Oct 2016
837
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Corrections and additions since last lecture
Graded and re-graded thetest
Check syllabus to see howgrades are computed
Homework for chapter 6 duebefore class
Exchanged e-mails and hadoffice hours (videoconference)
937
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
This and that
Read from a file
Objectives are fairly straightforward
Read strings from a data file
First string is the key
Second string is the plain text
Output plain and ldquoencryptedrdquostrings to the screen in a particularorder
Submit your source code
This is a single person effort (not ateam effort)
Any questions or problems
1037
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
Flow of control
There are limited number of different ldquoflow of controlrdquo
Sequential ndash instructions are executed in order
Function calls ndash program execution is transferred to a functionand then returned (with or without a return value)
Selection ndash some instructions are executed but others are not
Looping ndash a set of instructions is executed more than once
1137
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
The ldquoifrdquo statement
The ldquoifrdquo statement evaluates a conditional as ldquotruerdquo orldquofalserdquoWhen the conditional is ldquotruerdquo then the next statement isexecutedThe conditional can be simple or complex
Examples of ldquoifrdquo statementsif ( true ) cout ltlt The condition is true ltlt endl
if ( true )
cout ltlt The condition is true ltlt endl
if ( a gt 3 )
cout ltlt a is greater than 3 ltlt endl
if ( (a lt 2) || (3 lt a) )
cout ltlt a is less than 2 OR greater than 3 ltlt endl
if ( (a lt 2) ampamp (3 lt a) )
cout ltlt a is less than 2 AND greater than 3 (impossible) ltlt endl
1237
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
What if we want to execute more than one statement
We look at what defines a statement
if ( true ) cout ltlt The condition is true ltlt endl
else cout ltlt The condition is false ltlt endl
if ( a gt 3 )
cout ltlt a is greater than 3 ltlt endl
cout ltlt And we can do other things ltlt endl
else
cout ltlt a is NOT greater than 3 ltlt endl
cout ltlt As well when the condition is false ltlt endl
1337
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
Basic looping structures
while loopwhile ( conditional) statements with changerfor loopfor (initial conditional changer) statements
do while loopdo statements with changer while (conditional)
Handcrafted (which we wonrsquot go into)
1437
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
The ldquoinfiniterdquo loop
There may be times when you want a loop to repeat but theterminate conditions are too hard to make into a set ofcomparisonsstdstring fileName = tmptemptxt
stdifstream inputFile
int data = 0
inputFileopen(fileNamec_str())
for ( )
data ltlt inputFile
if (data == 37)
break
else
if ( data == 16)
continue
data += 42
break ldquobreaksrdquo out of the current control structure continue
ldquocontinuesrdquo execution at the top of the control structure
1537
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
What if there is more than one ldquootherrdquo case
The ldquoifrdquo statement handles exactly one conditional and thenexecutes code based on whether that conditional is ldquotruerdquo orldquofalserdquoldquoifrdquo statements can be nested to create very complex conditionalexpressionsBut how can we efficiently handle many conditionals at onceEnter the ldquoswitchrdquo statement The ldquoswitchrdquo statementcompares one expression against a number of conditions andexecutes code when the condition is true Wersquoll play with the
ifcpp and switchcpp programs
1637
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
Notional ldquoswitchrdquo structure structure
The ldquoswitch statement is aselection control structure formulti-way branching
IntegralExpression ndash anyexpression that can bereduced to an integer value
case Constant ndash anyconstant value that is thesame type as theIntegralExpression
default ndash the ldquocaserdquo whenno other cases match
Image from [2]
1737
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
Same image
Image from [2]
1837
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
Example of a ldquoswitchrdquo statement
cin gtgt letter gtgt first gtgt second
switch (letter)
case rsquoArsquo
answer = (first + second)
cout ltlt first ltlt + ltlt second
ltlt is ltlt answer ltlt endl
break
case rsquoSrsquo
answer = (first - second)
cout ltlt first ltlt - ltlt second
ltlt is ltlt answer ltlt endl
break
1937
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
More details about the switch statement
The value ofIntegralExpression (of charshort int long or enumtype) determines whichbranch is executed
Case labels are constantintegral expressions
Several case labels canprecede a statement
Control branches to thestatement following thecase label that matches the
value of IntegralExpression
Control proceeds throughall remaining statementsincluding the defaultunless redirected with break
If no case label matches thevalue of IntegralExpressioncontrol branches to thedefault label if present
Otherwise control passes tothe statement following theentire switch statement
Forgetting to use break can cause logical errors
2037
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Things from the past
Misc things about break and continue statements
A break statement can beused in switch or any ofthe 3 looping structures
It causes an immediateexit from the currentstructure
If used in a nestedstructure it only exitsthe current structure
A continue statement canonly be used in a loopingstructure
It terminates the currentiteration but not theentire loopIn a ldquoforrdquo loop theupdate is still doneIn a ldquodo ndash whilerdquo theexit condition is tested
Indiscriminate use of break and continue can lead to confusingcode
2137
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
More about C++ operators
C++ operators we will know and love
There are a lot of declaredoperators in C++ Over the nextfew months will will learn aboutthe ones in red and possibly theones in green
Image from [1]
2237
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
More about C++ operators
Same image
Image from [1]
2337
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
More about C++ operators
With so many operators which has precedence
Not all operations are left toright Precedence can be affectedby using parenthesis
Image from [3]
2437
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
More about C++ operators
Same image
Image from [3]
2537
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
More about C++ operators
With so many operators which has precedence
Not all operations are left toright Precedence can be affectedby using parenthesis
Image from [3]
2637
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
More about C++ operators
Same image
Image from [3]
2737
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
More about C++ operators
Specialized C++ operators
What do these expressions do and why
Interesting expressions232 (alpha + beta)delta = 2 12
Confusing expressions
int1 = 14 int2 =++int1
int1 = 14 int2 =int1++
When in doubt fire up CodeBlocks and test them out
2837
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
fragile
Bit operators
What do these fragments produce and why
When in doubt fire up CodeBlocks and test them out
2937
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
fragile
What if we donrsquot like the type of our variable
There may be some cases where we want the compiler to changethe ldquotyperdquo of our dataThis is known as ldquocastingrdquo the variable It really is changing thevalue of the variable to the desired type
Functional notationintVar = int(floatVar)
Prefix notationintVar = (int) floatVar
Keyword notationintVar = static castltintgt(floatVar)
Keyword notation is gaining popularity because it is easy to locatein multiple files
3037
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
fragile
What are the mechanics behind ldquocastingrdquo values
There are only two cases
If there is only one data type involved
Trivial case nothing happens
If there is more than one data type involved
Each data type is promoted to the next higher data typeuntil we have a trivial caseOrder of data type promotion int unsigned int long
float double long double
Casting also happens behind the scenes with conditionals Bestadvice is to compare like types
3137
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
fragile
A special C++ operator
This type of logic happens a lot
if (someConditional)
c = something
else
c = somethingElse
If fact it is so common in the CC++ world that it was added tothe language It looks like this
c = (someConditional) something somethingElse
Reduces likelihood of typing errors
3237
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Break time
Take about 10 minutes
3337
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Practice exercises
Programs to load into CodeBlocks and get running
1 ifcpp (look at and understand how nested sequential ldquoifsrdquowork)
2 switchcpp (expand the program to print the first stanza whena 0 is entered)
3 switchescpp (expand to support multiple case labels orsomething else)
Others if you have time
3437
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Q amp A time
ldquorsquoThe Answer to the GreatQuestion Of Life the Universeand Everything is forty-tworsquo said DeepThought with infinite majestyand calmrdquoDouglas Adams TheHitchhikerrsquos Guide to theGalaxy
3537
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
What have we covered
Returned and discussed test 01Covered looping statements indifferent formsTalked about low level C++operatorsTalked about changing the type ofvariables (casting)Chapter 7 homework before class
Next time Chapter 8
3637
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
References I
[1] Richard Smith et al Working draft standard for programminglanguage c++ ISOIEC JTC1SC22WG21 document N4296 (2015)
[2] Sylvia Sorkin Programming and problem solving with c++Teacher Resource Jones and Barlett Learning 2014
[3] C++ Staff C++ operator precedencehttpencppreferencecomwcpplanguage
operator_precedence 2016
3737
Test Results Schedule Miscellanea Control Structs Addrsquol Operrsquos Break Hands on Q amp A Conclusion References Files
Files of interest
1 ifcpp (just to start)
2 switchcpp (to expand)
3 switchescpp (to expand)
4 Programming assignment 003
include lt iostream gt
using namespace std
int main ()
int inputInt
cout ltlt Enter a 2 or 4 or 6
cin gtgt inputInt
cout ltlt You entered ltlt inputInt ltlt endl
cout ltlt Excerpts from Robert Burns To A Mouse On Turning Her Up In Her Nest With The Plough ltlt endl
if ( inputInt == 2 )
cout ltlt O what a panics in thy breastie
else
if ( inputInt == 4 )
cout ltlt Wi bickering brattle
else
if ( inputInt == 6 )
cout ltlt Wi murdring pattle
else
cout ltlt Youre messing with me
cout ltlt endl
return 0
Chuck Cartledge
switchcpp
include lt iostream gt
using namespace std
httpwwwrobertburnsorgworks75shtml
int main ()
int inputInt
cout ltlt Enter a 2 or 4 or 6
cin gtgt inputInt
cout ltlt You entered ltlt inputInt ltlt endl
cout ltlt Excerpts from Robert Burns To A Mouse On Turning Her Up In Her Nest With The Plough ltlt endl
switch ( inputInt )
case 2
cout ltlt O what a panics in thy breastie
break
case 4
cout ltlt Wi bickering brattle
break
case 6
cout ltlt Wi murdring pattle
break
default
cout ltlt Youre messing with me
cout ltlt endl
return 0
Chuck Cartledge
switchescpp
Program Switches demonstrates the use of the Switch
statement
include lt iostream gt
using namespace std
int main ()
char letter
int first
int second
int answer
cout ltlt Enter an A for addition or an S for
ltlt subtraction followed by two integer numbers
ltlt endl ltlt Press return Enter a Q to quit ltlt endl
cin gtgt letter
while ( letter = Q )
cin gtgt first gtgt second
switch ( letter )
case A answer = ( first + second )
cout ltlt first ltlt + ltlt second
ltlt is ltlt answer ltlt endl
break
case S answer = ( first - second )
cout ltlt first ltlt - ltlt second
ltlt is ltlt answer ltlt endl
break
cin gtgt letter
return 0
Chuck Cartledge
CSC-201 Fall 2016Assignment 3 File Based Address Book
Due Oct 4 2016
Dr Chuck Cartledge
September 21 2016 at 856am
Contents
1 Explanation 1
2 Assignment 1
3 What to submit 3
A Sample files 3
1 Explanation
You will be creating an address book for an absent minded professor This address book willserve as a basis for later programming assignments
The professor has a spotty memory and only remembers parts of things Things likefirst name middle name last name telephone numbers and addresses He remembers apart of each of these things but not the whole thing
He needs a program that will read a comma separated file (where each line in the filecontains all the information he tracks) and then searches whichever selected field he thinkshe remembers for the text he enters
The program needs to print out any and all matches from the address book He hasstarted the program and needs you to finish it
2 Assignment
These are the program requirements
1 Modify the attached interactive program to read the contents of the file
addressBooktsv
The file is attached and contains three silly contacts
2 Modify the program to
(a) Allow the professor to search any field Using
A to search the address field
P to search the phone number field
M to search the middle name field
L to search the last name field
(He got the first name search pretty much done)
(b) Allow the professor to enter upper or lower case command letters
3 The program shall print to standard out See the files section (see Section A) for allfiles Remember your output must go to standard out
4 The program should be properly documented (check the index for page references towhat constitutes good documentation)
Because the professor is basically lazy he will be using IO redirection to test the pro-gram The redirection will look like this
yourCompiledProgram lt addressBookcntrl 1gtnul 2gt resultFile
diff resutltFile goldenFile
It is the results of the diff command that will determine your grade
2
One of the common things about most modern operating systems (OSs) is their use of acommon set of values for file descriptors File descriptors are used by the OS as indices intoa list of queues for processing IO When an application wants to do any IO the applicationgets a file descriptor from the OS and then uses that file descriptor as needed The OS isresponsible for ensuring that the operation goes according to the applicationrsquos direction Itis possible that the OS will not complete an action if the application crashes or does notcleanly end its use of the file descriptorA user can access the preset OS file descriptors outside the application Here is a list ofnormal preset file descriptors
Name Number unistdh stdioh iostreamStandard input 0 STDIN FILENO stdin cinStandard output 1 STDOUT FILENO stdout coutStandard error 2 STDERR FILENO stderr cerr
About file descriptors
Sometimes yoursquoll neither want nor need to save the output from a program Essentiallyyoursquoll want to throw it away because it has no value Most operating systems (OSs) havea special place or syntax for ldquothrowing things awayrdquo An OS supports capturing outputfrom Standard Output Standard Error file descriptors and then redirecting those outputs tosomewhereHere are the special places where output can be redirected to and then lost by the OS
OS PlaceWindows nulnix devnull
About throwing things away
3 What to submit
The C++ source code that meets the assignment requirements
A Sample files
This is a sample input files
bull addressBookcntrl
3
FElseFFirstp12FSomeFhopesQ
TCC Staff
bull addressBooktsv
bull readAddressBook01cpp
4
First NameMiddle NameLast Name(123)456-78905225 Figueroa Mountain Rd Los Olivos CA 93441Someone elseElizaDreams789-123-4567Slaughterville OKSome closeTo ElizaDreams789-123-4567Tulsa OK
TCC Staff
readAddressBook01cpp
include lt iostream gt
include lt fstream gt
bool readARecord ( std ifstream amp in std string amp fName std string amp mName std string amp lName std string amp pNumber std string amp addr )
void printARecord ( std ostream amp out std string fName std string mName std string lName std string pNumber std string addr )
std string normalizeText ( std string text )
bool isTextInText ( std string lookIn std string lookFor )
int main ()
std string fileName = addressBooktsv
std string command
std string firstName
std string middleName
std string lastName
std string phoneNumber
std string address
std string search
std ifstream input
bool moreData = true
bool foundMatch
input open ( fileName c_str ())
command =
while ( command = Q )
std cout ltlt Enter a command F to search first name Q to quit
std cin gtgt command
if ( command == Q )
break
input clear ()
input seekg ( 0 std ios beg )
switch ( command at ( 0 ))
case F
std cout ltlt