Computing with Services CS 696 – Services Computing Fall 2008
CS 140 Introduction to Computing I
description
Transcript of CS 140 Introduction to Computing I
CS 140CS 140Introduction to Computing Introduction to Computing IIInstructor: Bill WhiteInstructor: Bill White Engineering Building Engineering Building 30413041 (618)650-3483 (618)650-3483 [email protected] [email protected]
Office Hours:Office Hours:MW 8:00-9:30AM & MW 8:00-9:30AM &
2:00-3:00PM2:00-3:00PMTR 8:00-10:00AM & TR 8:00-10:00AM &
12:30-2:00PM12:30-2:00PMand by appointmentand by appointment
TextbookTextbook
IntroductionIntroductionCS 140CS 140 Page Page 22
Tentative Syllabus
WEEK 1WEEK 1Intro to Intro to
HardwareHardware, ,
Software, Software, & C++& C++
WEEK 2WEEK 2VariablesVariables
, Data , Data Types, & Types, &
I/OI/O
WEEK 3WEEK 3If-Else, If-Else,
Looping, Looping, & &
Program Program StyleStyle
WEEK 4WEEK 4Nested Nested Ifs & Ifs &
SwitchesSwitches
WEEK 5WEEK 5For-For-
Loops, Loops, Nested Nested
Loops, & Loops, & Infinite Infinite LoopsLoops
EXAM EXAM #1#1
WEEK 6WEEK 6Top-Top-Down Down
Design & Design & PredefinePredefine
d d FunctionsFunctions
WEEK 7WEEK 7Function Function DefinitionDefinitions & Black s & Black
BoxesBoxes
WEEK 8WEEK 8Local Local
Variables Variables & Void & Void
FunctionsFunctions
WEEK 9WEEK 9Call-by-Call-by-
ReferencReference & More e & More
Black Black BoxesBoxes
WEEK WEEK 1010
Function Function Design, Design, Testing, Testing,
& & DebugginDebuggin
gg
EXAM EXAM #2#2
WEEK WEEK 1111
Files & Files & Stream Stream
I/OI/O
WEEK WEEK 1212
Character Character I/O & I/O &
Intro to Intro to ArraysArrays
WEEK WEEK 1313
Arrays in Arrays in One or One or More More
DimensioDimensionsns
WEEK WEEK 1414
Character Character StringsStrings
WEEK WEEK 1515
Standard Standard String String ClassClass
EXAM EXAM #3#3
AND THEN…AND THEN…
A A COMPREHENSIVCOMPREHENSIV
E FINAL E FINAL EXAM!!!EXAM!!!
IntroductionIntroductionCS 140CS 140 Page Page 33
GradingGrading
Grading ScaleGrading Scale900-1000 points A900-1000 points A
800-899 points B800-899 points B700-799 points C700-799 points C600-699 points D600-699 points D
0-599 points F0-599 points F
100 points - Laboratory Grade100 points - Laboratory Grade400 points - Programming 400 points - Programming AssignmentsAssignments100 points - Quizzes100 points - Quizzes
400 points - Exams400 points - Exams
1000 points total!1000 points total!
IntroductionIntroductionCS 140CS 140 Page Page 44
Only the student and the instructor may see the
student’s actual code!!!
THE THE LATELATECS 140 CS 140
STUDENSTUDENTT
Assignments will be accepted late only for documented medical
reasons!!!
Late Policy andLate Policy andAcademic MisconductAcademic Misconduct
Chapter 1Chapter 1Introduction to Computers Introduction to Computers and C++ Programmingand C++ Programming
Goals:Goals:
• To introduce the fundamental hardware and To introduce the fundamental hardware and software components of a computer systemsoftware components of a computer system
• To describe the role of compilers in high-level To describe the role of compilers in high-level programmingprogramming• To examine the use of algorithms in program designTo examine the use of algorithms in program design
• To define the software life cycleTo define the software life cycle
• To introduce the C++ programming languageTo introduce the C++ programming language
Chapter 1Chapter 1CS 140CS 140 Page Page 66
Computer Hardware: PC OutputComputer Hardware: PC Output
Cathode Ray Tube Display: Uses electron guns aimed at hundreds of
thousands of RGB phosphor pixels to render images
Menu ButtonLeft & Right Arrow Buttons: For
moving between on-screen display options
Select Button: For selecting on-screen options
Power Light-Emitting Diode
Power Button
The monitor is the principal device for providing computer output to a user.
Chapter 1Chapter 1CS 140CS 140 Page Page 77
Computer Hardware: PC InputComputer Hardware: PC Input
Keyboard: For textual, numerical, and complex control input
Input devices are employed to provide the user with a means for
supplying the computer with information.
Mouse: For simple interactive control input
Chapter 1Chapter 1CS 140CS 140 Page Page 88
Computer Hardware: PC Tower Computer Hardware: PC Tower FrontFront
5.25” Drive Bay Door: For memory expansion
CD/DVD Drive: For optical memory
CD/DVD Eject Button3.5” Drive Bay Door: For memory
expansionIEEE 1394 Port: For plugging in 4-pin devicesDiskette Drive
Diskette Eject Button
Power Button
USB Ports: For plugging in USB (Universal Serial Bus) devices, such as a
digital camera
Chapter 1Chapter 1CS 140CS 140 Page Page 99
Computer Hardware: PC Tower Computer Hardware: PC Tower BackBack
Power Connector
Voltage Switch
Mouse Port
Keyboard PortUSB Ports
Serial Port (e.g., camera)Parallel Port (e.g.,
printer)Monitor PortUSB Ports
Microphone JackHeadphones/Speaker Jack
Audio Input JackTelephone Jack
Modem Jack
Cable Lock SlotCase Cover Shipping Screw
Microsoft Certificate of Authenticity: Contains Windows product key
Ethernet/DSL/Cable Modem Jack
Add-In Card Retention Screw
Chapter 1Chapter 1CS 140CS 140 Page Page 1010
Computer Hardware: MemoryComputer Hardware: Memory
Read-Only Memory
Integrated circuitry that contains non-
volatile, unchangeable
data.Basic Input/Output SystemSoftware stored on ROM,
which serves as an interface between the
hardware and the operating system.
Removable DrivesPortable devices that facilitate sharing and securing data. Types include magnetic
(e.g., floppy disks and Zip disks), optical (e.g., CDs and DVDs), and solid-state (e.g., flash-memory cards).
Network StorageRemote memory on other machines, with retrieval and update capabilities
provided.
Hard DrivePermanently
installed magnetic platters, with
larger capacity and faster speed than removable drives.
Physical Random-Access Memory
Integrated circuitry that provides fast access to stored
information, but that perpetually requires
refreshing.
Virtual MemoryAn operating
system technique for “pretending”
that RAM is larger than it really is by
making room for new data by
moving data that hasn’t been
accessed lately to the hard drive.
Cache MemoryVery fast (and very expensive) circuitry to speed up access to
stored data. L2 is about twice the speed of RAM, while L1 is about 7
times faster.
Central Processing Unit RegisterMemory cells built right into the CPU, holding data that the processor needs
immediately.
Chapter 1Chapter 1CS 140CS 140 Page Page 1111
Computer Hardware: Computer Hardware: ProcessorProcessorCPU
The Central Processing
Unit
Integer ALUHandles integer arithmetic
Floating-Point ALUHandles non-integer
arithmetic
RegistersStores data & instructions
Execution UnitManages instruction
traffic32-Bit BusesSimultaneously pipelines 2 data
streams
Data CacheFast storage
for data
Code CacheFast storage for
instructions
Instruction UnitPrefetches &
decodes instructions Branch Predictor“Guesses” next instruction to be
executed
Primary CacheFast memory for
data & instructions that are anticipated to
be needed
Bus InterfaceSeparates and forwards
incoming data & instructions; collates outgoing data &
instructions
64-Bit BusConduit through which CPU/RAM traffic travels
Chapter 1Chapter 1CS 140CS 140 Page Page 1212
Key ‘P’ struckKey ‘P’ struck
Computer SoftwareComputer Software
HardwareDirect access to circuitry, disks, mouse, keyboard, monitor, etc.
Operating SystemSoftware that relays messages
between application and hardware
ApplicationSoftware that performs high level
operations (computation, graphics, etc.)
““Hey, OS!Hey, OS!
key ‘P’!”key ‘P’!”
““Hey, App!Hey, App!
key ‘P’!”key ‘P’!”
For a game, For a game, send explosion send explosion
sound to sound to speaker and speaker and
new pixel new pixel values to values to monitormonitor
Contact Contact appropriate appropriate hardwarehardware
Specify Specify resulting resulting responseresponse
Note that for a word processor application, the result Note that for a word processor application, the result would have been the same, except the final step would would have been the same, except the final step would have involved inserting a ‘P’ character in memory and have involved inserting a ‘P’ character in memory and
updating the screen display.updating the screen display.
Chapter 1Chapter 1CS 140CS 140 Page Page 1313
Low-Level Programming Low-Level Programming LanguagesLanguages
A computer processor is A computer processor is notnot smart! smart!
Its vocabulary is limited to a simple Its vocabulary is limited to a simple “machine language” consisting of a small “machine language” consisting of a small number of simple commands.number of simple commands.
Move this number over
there!
Move that number over
here!
Add this number to
that number!
Check to see if this
number is zero!
Chapter 1Chapter 1CS 140CS 140 Page Page 1414
ProgrammingProgrammingTo get the computer to perform To get the computer to perform sophisticated operations, the programmer sophisticated operations, the programmer writes programs that tell the processor writes programs that tell the processor the sequence of primitive steps to take to the sequence of primitive steps to take to get a result.get a result.
001001010110101010101010101010100001111110011100101111000001101010010010111010100010100100001101011001010100110101100101010010101001010010101011010010101000100101010101010101010101001010101001
13 01946.372
Programming in Programming in machine language machine language is a binary pain, so is a binary pain, so higher level higher level languages have languages have been developed to been developed to make the job of the make the job of the programmer more programmer more efficient and more efficient and more effective!effective!
Chapter 1Chapter 1CS 140CS 140 Page Page 1515
Compiling a High-Level Compiling a High-Level ProgramProgram
A program caller a “compiler” is used to A program caller a “compiler” is used to translate your “source program” (in a translate your “source program” (in a language like C++) into an “object language like C++) into an “object program” (in your system’s machine program” (in your system’s machine language).language).#include <iostream>
using namespace std;void main(){ int x, y; cout << “Enter two integers: ”; cin >> x >> y; if (x > y) cout << x << “ is the largest!”; else cout << y << “ is the largest!”; return;}
LEXICALANALYSIS
Split the source
program into words like “void”, “x”, “>”, and “;”.
PARSINGAnalyze the grammatical syntax of the
source program (e.g., “if (x > y)”makes sense, but “if (x > ) y”
doesn’t).
CODECODEGENERATIONGENERATIONGenerate an Generate an equivalent equivalent program in program in
machine machine language.language.
110101000101100011000010010110110100010101011110010101011100000010011100101011001110101010111001010100101010101000000110110111011101010100111110101010101001001001010000010101010101000000101111100101100001011101010101010100010101111110010100100100101000
Source ProgramSource Program Object ProgramObject Program
Chapter 1Chapter 1CS 140CS 140 Page Page 1616
Linking and LoadingLinking and LoadingAfter being compiled, the object program After being compiled, the object program must be “linked” (i.e., connected to must be “linked” (i.e., connected to other compiled code from libraries, like other compiled code from libraries, like math functions or input/output math functions or input/output operators) and then “loaded” into main operators) and then “loaded” into main memory for execution.memory for execution.
SourceSource
ProgramProgramObjectObject
ProgramProgramLinkedLinked
ProgramProgramCompiledCompiledLibraryLibrary
ProgramsPrograms
COMPILECOMPILE
LINKLINKLOADLOAD
Chapter 1Chapter 1CS 140CS 140 Page Page 1717
AlgorithmsAlgorithmsAfter defining a problem that the After defining a problem that the programmer wants the computer to solve, programmer wants the computer to solve, the programmer must first design an the programmer must first design an algorithmalgorithm, a sequence of precise , a sequence of precise instructions that lead to a solution.instructions that lead to a solution.Problem: Find the largest value in a list of numbers.Problem: Find the largest value in a list of numbers.
Algorithm:Algorithm:
1) Retrieve the list of numbers.1) Retrieve the list of numbers.
2) Consider the first number the largest value so far.2) Consider the first number the largest value so far.
3) Starting at the second number in the list, compare3) Starting at the second number in the list, compare the number in the list to the largest value so far;the number in the list to the largest value so far; if it’s larger, then make if it’s larger, then make itit the largest value so far. the largest value so far.
4) After examining all of the numbers, announce the4) After examining all of the numbers, announce the largest value so far - it’s the largest in the list!.largest value so far - it’s the largest in the list!.
4747
2828
5656
61613030
1919
4747
5656
6161
4747
5656??????????
6161 LARGEST!LARGEST!
Chapter 1Chapter 1CS 140CS 140 Page Page 1818
Another AlgorithmAnother AlgorithmProblem: Find the phone number of a specific person in an Problem: Find the phone number of a specific person in an alphabetized phonebook.alphabetized phonebook.
Algorithm:Algorithm:
1) Get the phonebook.1) Get the phonebook.
2) Crack what’s left of the phonebook open to the middle page.2) Crack what’s left of the phonebook open to the middle page.
3) Check to see if the name you’re seeking is on that page. If so,3) Check to see if the name you’re seeking is on that page. If so,announce the phone number and you’re done!. Otherwise,announce the phone number and you’re done!. Otherwise,throw away the “impossible” half of the phonebook, andthrow away the “impossible” half of the phonebook, andrepeat the process, starting at step #2.repeat the process, starting at step #2.
4) If the 4) If the entireentire phonebook is ever thrown out, then the person is phonebook is ever thrown out, then the person isunlisted!unlisted!
Chapter 1Chapter 1CS 140CS 140 Page Page 1919
The Software Life CycleThe Software Life CycleSpecificationSpecification
Clearly state the purpose of the Clearly state the purpose of the software, including full details of software, including full details of
the problem being solved. the problem being solved.
DesignDesignDevelop a solution to the problem, Develop a solution to the problem,
modularizing it and determining modularizing it and determining specific pre- and post-conditions. specific pre- and post-conditions.
CodingCodingProgram the modules using a bottom-Program the modules using a bottom-up approach (with dummy drivers) or a up approach (with dummy drivers) or a
top-down approach (with stubs). top-down approach (with stubs).
TestingTestingDesign test scenarios for individual Design test scenarios for individual
modules, interaction between modules, interaction between modules, and the entire program. modules, and the entire program.
MaintenanceMaintenanceRespond to “bugs” and “sugs”, Respond to “bugs” and “sugs”,
and determine when the and determine when the software has become obsolete. software has become obsolete.
DOCUMENTATION!!! DOCUMENTATION!!!
Chapter 1Chapter 1CS 140CS 140 Page Page 2020
Introduction to C++Introduction to C++Ancient LanguagesAncient LanguagesFortran - Great for scientific computationsFortran - Great for scientific computationsCOBOL - Great for business file processingCOBOL - Great for business file processingVery special purpose, not good in generalVery special purpose, not good in general
Old LanguagesOld LanguagesC - General purpose language for UNIX systemsC - General purpose language for UNIX systemsPascal - General purpose language for PCsPascal - General purpose language for PCsEmphasis upon procedures instead of dataEmphasis upon procedures instead of data
Modern LanguagesModern LanguagesC++ - Object-oriented version of CC++ - Object-oriented version of CJava - Object-orientation with networking emphasisJava - Object-orientation with networking emphasisEmphasis upon the objects being manipulatedEmphasis upon the objects being manipulated
Chapter 1Chapter 1CS 140CS 140 Page Page 2121
#include <iostream> // This library facilitates input & output.#include <math.h> // This library enables math functions, like sqrt.
using namespace std; // Use the standard C++ naming conventions
void main() // Every C++ program must have a "main" function.{ // Opening brace to contain main's statements. double nbr; // Declare variable "nbr" to be an integer. double root; // Declare variable "root" to be a long real number.
nbr = 2.0; // Set value of nbr to be 2. root = sqrt(nbr); // Calculate square root of nbr.
cout << " The square root of " // Output a message to the memory file << nbr << " is " << root // associated with the monitor (i.e., cout), << endl << endl; // including nbr, root, and a skipped line.
cout << "Enter a number: "; // Ask the user for a value for nbr. cin >> nbr; // Input from file associated with keyboard (cin). root = sqrt(nbr); // Calculate the square root of nbr's new value.
cout << "The square root of " // Output a message to the cout file << nbr << " is " << root // concerning the values of nbr and root, << endl << endl << endl; // followed by two skipped lines.
return; // Terminate the program's execution.} // Closing brace to indicate end of main function.
#include <iostream> // This library facilitates input & output.#include <math.h> // This library enables math functions, like sqrt.
using namespace std; // Use the standard C++ naming conventions
void main() // Every C++ program must have a "main" function.{ // Opening brace to contain main's statements. double nbr; // Declare variable "nbr" to be an integer. double root; // Declare variable "root" to be a long real number.
nbr = 2.0; // Set value of nbr to be 2. root = sqrt(nbr); // Calculate square root of nbr.
cout << " The square root of " // Output a message to the memory file << nbr << " is " << root // associated with the monitor (i.e., cout), << endl << endl; // including nbr, root, and a skipped line.
cout << "Enter a number: "; // Ask the user for a value for nbr. cin >> nbr; // Input from file associated with keyboard (cin). root = sqrt(nbr); // Calculate the square root of nbr's new value.
cout << "The square root of " // Output a message to the cout file << nbr << " is " << root // concerning the values of nbr and root, << endl << endl << endl; // followed by two skipped lines.
return; // Terminate the program's execution.} // Closing brace to indicate end of main function.
A A Sample Sample C++ C++ PrograProgramm
Chapter 1Chapter 1CS 140CS 140 Page Page 2222
Programming in Visual C+Programming in Visual C++ .NET+ .NETOur labs are set up Our labs are set up with PCs that run with PCs that run Visual C++ .NET, Visual C++ .NET, Microsoft’s version Microsoft’s version of the language that of the language that contains many user contains many user interface features interface features designed to designed to facilitate writing, facilitate writing, editing, compiling, editing, compiling, building, and building, and executing C++ executing C++ programs.programs.
Chapter 1Chapter 1CS 140CS 140 Page Page 2323
Starting Visual C++ .NETStarting Visual C++ .NET
Chapter 1Chapter 1CS 140CS 140 Page Page 2424
Creating a New C++ ProjectCreating a New C++ Project
ProgramXYZ
C:\temp
Chapter 1Chapter 1CS 140CS 140 Page Page 2525
Creating a Program FileCreating a Program File
ActualCode
Chapter 1Chapter 1CS 140CS 140 Page Page 2626
Editing the ProgramEditing the Program
// This program just says "Hi!"
#include <iostream> // Permits input/output operations#include <cstring> // Permits string manipulation
using namespace std;
void main(){ char yourName[30];
cout << "What's Your Name?" << endl; cin >> yourName;
cout << endl << endl << "Hi, " << yourName << "!!!" << endl << endl;}
Note that…Comments are Green
C++ Keywords are BlueRegular Code is Black
Chapter 1Chapter 1CS 140CS 140 Page Page 2727
Compiling, Linking, and Compiling, Linking, and LoadingLoading
Chapter 1Chapter 1CS 140CS 140 Page Page 2828
Executing the ProgramExecuting the Program
At this point the programmer could edit the program further, copy it to
a diskette, or submit it as a completed assignment via the student’s assigned dropbox.
Chapter 2Chapter 2C++ BasicsC++ Basics
Goals:Goals:
• To introduce the concept of a variable and its To introduce the concept of a variable and its assignmentassignment• To explore primitive input and output operationsTo explore primitive input and output operations
• To survey the primitive data types in C++To survey the primitive data types in C++
• To examine the use of arithmetic expressionsTo examine the use of arithmetic expressions
• To define flow of control via conditionals and loopsTo define flow of control via conditionals and loops
Chapter 2Chapter 2CS 140CS 140 Page Page 3030
VariablesVariables
Variables are memory locations within RAM.Variables are memory locations within RAM.
RAMRAMRAM is divided RAM is divided
into 8-bit into 8-bit segments called segments called
bytesbytes..
Each byte is Each byte is numbered with a numbered with a binary binary addressaddress..
Binary Address
00000000
Binary Address
11111111
When a program When a program variable is variable is declareddeclared, ,
adequate space in RAM adequate space in RAM is reserved for it.is reserved for it.
The variable is named The variable is named with an with an identifieridentifier and and can be given a can be given a valuevalue..
That value is stored at That value is stored at its memory address, its memory address, which is known as a which is known as a
pointerpointer..Variable of type char
Variable of type int
Variable of type double
Chapter 2Chapter 2CS 140CS 140 Page Page 3131
IdentifiersIdentifiersVariables names, or identifiers, must start Variables names, or identifiers, must start with an underscore or an alphabetic symbol, with an underscore or an alphabetic symbol, and all of the remaining symbols must be and all of the remaining symbols must be alphanumeric or underscores.alphanumeric or underscores.
Chapter 2Chapter 2CS 140CS 140 Page Page 3232
Reserved C++ Keywords -Reserved C++ Keywords -Can’t Be Used As Identifiers!Can’t Be Used As Identifiers!
asmasm auto auto bool bool breakbreakcasecase catch catch char char class classconstconst const const__castcast continue continue default defaultdeletedelete do do double double dynamicdynamic__castcastelseelse enum enum explicit explicit extern externfalsefalse float float for for friend friendgotogoto if if inline inline int intloglog long long mutable mutable namespacenamespacenewnew operator operator private private protected protectedpublicpublic register register reinterpret_cast reinterpret_cast return returnshortshort signed signed sizeof sizeof static staticstaticstatic__castcast struct struct switch switch template templatethisthis throw throw true true try trytypedeftypedef typeid typeid typename typename union unionunsignedunsigned using using virtual virtual void voidvolatilevolatile wchar_t wchar_t while while
Chapter 2Chapter 2CS 140CS 140 Page Page 3333
Variable DeclarationsVariable DeclarationsVariables must be declared before being Variables must be declared before being used in a program.used in a program.
intint count; count;floatfloat salaryPerWeek; salaryPerWeek;charchar middleInitial; middleInitial;intint nbr_of_rings, nbr_of_knocks; nbr_of_rings, nbr_of_knocks;floatfloat MonPay, TuePay, WedPay, MonPay, TuePay, WedPay, ThuPay, FriPay;ThuPay, FriPay;doubledouble measurement1, measurement2; measurement1, measurement2;
Chapter 2Chapter 2CS 140CS 140 Page Page 3434
Assignment StatementsAssignment Statements
Variables may be “assigned” values via the Variables may be “assigned” values via the assignment operator (=) in assignment assignment operator (=) in assignment statements.statements.count = 0;count = 0;salaryPerWeek = 40 * salaryPerHour;salaryPerWeek = 40 * salaryPerHour;middleInitial = ‘W’;middleInitial = ‘W’;nbr_of_rings = 2 * nbr_of_knocks - 1;nbr_of_rings = 2 * nbr_of_knocks - 1;MonPay = TuePay = WedPay = 47.25F;MonPay = TuePay = WedPay = 47.25F;ThuPay = FriPay = (ThuPay = FriPay = (floatfloat)62.75;)62.75;measurement2 = measurement1 / count;measurement2 = measurement1 / count;
Chapter 2Chapter 2CS 140CS 140 Page Page 3535
Initializing VariablesInitializing VariablesVariables may be “initialized” in their Variables may be “initialized” in their declarations to possess specific values.declarations to possess specific values.
intint value = 0; value = 0;floatfloat Radius = 16.00F; Radius = 16.00F;boolbool flag = flag = falsefalse;;doubledouble errorMargin = 0.00000003; errorMargin = 0.00000003;charchar firstltr = ‘A’, lastltr = ‘Z’; firstltr = ‘A’, lastltr = ‘Z’;intint loserCount(0), winnerCount(0); loserCount(0), winnerCount(0);floatfloat GPA(4.00F); GPA(4.00F);
Chapter 2Chapter 2CS 140CS 140 Page Page 3636
Output to the Monitor viaOutput to the Monitor via coutcout
Values may be output to the monitor by means Values may be output to the monitor by means of of output statementsoutput statements that use the output that use the output operator (<<) to stream to the output fileoperator (<<) to stream to the output file cout cout..
cout << 1492;cout << 1492;intint val = 97; val = 97;cout << val;cout << val;cout << 1997 << “was great!”;cout << 1997 << “was great!”;cout << “I made a fortune!”;cout << “I made a fortune!”;
cout << val << “million\n\ndollars!”;cout << val << “million\n\ndollars!”;
cout << 1997 << “ was great!\n”;cout << 1997 << “ was great!\n”;cout << “I made a fortune!”;cout << “I made a fortune!”;
Output:Output: 14921492
Output:Output: 9797
Output:Output:
1997was great!I made a fortune!1997was great!I made a fortune!
Output:Output:
1997 was great!1997 was great!I made a fortune!I made a fortune!
Output:Output:
97million97million
dollars!dollars!
Chapter 2Chapter 2CS 140CS 140 Page Page 3737
Escape Escape SequencesSequences
\a \a Bell (alert)Bell (alert)
// Example EscapeSequence#include <iostream>using namespace std;
void main(){ cout << "1Aa\azzz\aZZZ" << endl; cout << "2Bb\bzzz\bZZZ" << endl; cout << "3Cc\nzzz\nZZZ" << endl; cout << "4Dd\rzzz\rZZZ" << endl; cout << "5Ee\tzzz\tZZZ" << endl; cout << "6Ff\'zzz\'ZZZ" << endl; cout << "7Gg\"zzz\"ZZZ" << endl; cout << "8Hh\\zzz\\ZZZ" << endl; return;}
When a character When a character value contains a value contains a character preceded by character preceded by a backslash (a backslash (\\), then it ), then it represents a represents a singlesingle symbol known as an symbol known as an escape sequence.escape sequence.
\b \b BackspaceBackspace\n \n New lineNew line\r \r Carriage returnCarriage return\t \t Horizontal tabHorizontal tab\' \' Single quotation markSingle quotation mark\" \" Double quotation markDouble quotation mark\\ \\ BackslashBackslash
Chapter 2Chapter 2CS 140CS 140 Page Page 3838
Formatting Real Number Formatting Real Number OutputOutputTo ensure that real numbers are output with To ensure that real numbers are output with decimal points, an integer part, and a specific decimal points, an integer part, and a specific number of decimal places, the following lines number of decimal places, the following lines should be included before outputting:should be included before outputting:
cout.setf(ios::fixed);cout.setf(ios::fixed);
cout.setf(ios::showpoint);cout.setf(ios::showpoint);
cout.precision(4);cout.precision(4);
Avoids Avoids Scientific Scientific Notation.Notation.
Shows Shows Decimal Decimal
PointPoint& Trailing & Trailing
Zeros.Zeros.Shows 4 Shows 4 DigitsDigits
After Decimal After Decimal Point.Point.
Chapter 2Chapter 2CS 140CS 140 Page Page 3939
SampleSampleReal Real Number Number Formatting Formatting ProgramProgram
//Example FormatFloats#include <iostream>using namespace std;
void main(){ cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(8); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl;
cout.precision(4); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl;
cout.precision(2); cout << 9876.543210 << endl; cout << 0.246813579 << endl; cout << 37.00000000 << endl << endl;
return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 4040
Input from the Keyboard viaInput from the Keyboard via cincinValues may be input from the keyboard by Values may be input from the keyboard by means of means of input statementsinput statements that use the input that use the input operator (>>) to stream from the input fileoperator (>>) to stream from the input file cin cin..//Example UserInput#include <iostream>using namespace std;
void main(){ int nbr; cin >> nbr;
char init1, init2, init3; cin >> init1 >> init2 >> init3;
float temp; cout << "Enter the temperature: "; cin >> temp;
return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 4141
Data Types - IntegersData Types - Integers//Example IntegerTypes#include <iostream>#include <limits.h> // Defines integer limits.using namespace std;
void main(){ int NTjurA = 5, NTjurB = INT_MAX, NTjurC = INT_MIN; cout << "REGULAR INTEGERS:" << endl << NTjurA << endl << NTjurB << endl << NTjurC << endl << endl;
long NNNNNTjurD = 5, NNNNNTjurE = LONG_MAX, NNNNNTjurF = LONG_MIN; cout << "LONG INTEGERS:" << endl << NNNNNTjurD << endl << NNNNNTjurE << endl << NNNNNTjurF << endl << endl;
short nTjurG = 5, nTjurH = SHRT_MAX, nTjurI = SHRT_MIN; cout << "SHORT INTEGERS:" << endl << nTjurG << endl << nTjurH << endl << nTjurI << endl << endl;
unsigned int UnNTjurJ = 5, UnNTjurK = UINT_MAX; cout << "UNSIGNED INTEGERS:" << endl << UnNTjurJ << endl << UnNTjurK << endl << endl << endl; return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 4242
Data Types - Data Types - Floating-PointFloating-Point
//Example FloatTypes#include <iostream>#include <float.h> // Defines float limits.using namespace std;
void main(){ float floA = 9.87654321F, floB = FLT_EPSILON, floC = FLT_MAX, floD = FLT_MIN; cout << "REGULAR FLOATS:" << endl << floA << endl << floB << endl << floC << endl << floD << endl << endl;
double dubE = 9.87654321, dubF = DBL_EPSILON, dubG = DBL_MAX, dubH = DBL_MIN; cout << "DOUBLE FLOATS:" << endl << dubE << endl << dubF << endl << dubG << endl << dubH << endl << endl;
long double ldI = 9.87654321, ldJ = LDBL_EPSILON, ldK = LDBL_MAX, ldL = LDBL_MIN; cout << "LONG DOUBLE FLOATS:" << endl << ldI << endl << ldJ << endl << ldK << endl << ldL << endl << endl << endl;
return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 4343
Data Types - Characters and Data Types - Characters and BooleansBooleans//Example CharacterTypes#include <iostream>using namespace std;
void main(){ char chA = 'T'; char chB = '\t'; char chC = '\\';
cout << chA << chB << chC << endl << chB << chC << chA << endl << chC << chA << chB << endl << endl;
return;}
//Example BooleanTypes#include <iostream>using namespace std;
void main(){ bool booX = true; bool booY = false; bool booZ = (532 > 738);
cout << booX << endl << booY << endl << booZ << endl << endl;
return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 4444
//Example IncompatibleTypes#include <iostream>using namespace std;
void main(){ int NTjurA = 9.635F, NTjurB = 9.635, NTjurC = '&’, NTjurD = true; cout << NTjurA << '\t' << NTjurB << '\t' << NTjurC << '\t' << NTjurD << "\n\n";
float floE = 65, floF = 65.34, floG = 'Q’, floH = false; cout << floE << '\t' << floF << '\t' << floG << '\t' << floH << "\n\n";
double dubI = 14, dubJ = 14.92F, dubK = '?’, dubL = true; cout << dubI << '\t' << dubJ << '\t' << dubK << '\t' << dubL << "\n\n";
char chM = 3, chN = 3.1416F, chO = 3.1416, chP = true; cout << chM << '\t' << chN << '\t' << chO << '\t' << chP << "\n\n";
bool booQ = 467, booR = 467.927F, booS = 467.927, booT = 'w'; cout << booQ << '\t' << booR << '\t' << booS << '\t' << booT << "\n\n";
return;}
Type IncompatibilitiesType Incompatibilities//Example IncompatibleTypes#include <iostream>using namespace std;
void main(){ int NTjurA = 9.635F, NTjurB = 9.635, NTjurC = '&’, NTjurD = true; cout << NTjurA << '\t' << NTjurB << '\t' << NTjurC << '\t' << NTjurD << "\n\n";
float floE = 65, floF = 65.34, floG = 'Q’, floH = false; cout << floE << '\t' << floF << '\t' << floG << '\t' << floH << "\n\n";
double dubI = 14, dubJ = 14.92F, dubK = '?’, dubL = true; cout << dubI << '\t' << dubJ << '\t' << dubK << '\t' << dubL << "\n\n";
char chM = 3, chN = 3.1416F, chO = 3.1416, chP = true; cout << chM << '\t' << chN << '\t' << chO << '\t' << chP << "\n\n";
bool booQ = 467, booR = 467.927F, booS = 467.927, booT = 'w'; cout << booQ << '\t' << booR << '\t' << booS << '\t' << booT << "\n\n";
return;}
The compiler gives warning messages for each highlighted statement, but allows the program to run
nevertheless.
Chapter 2Chapter 2CS 140CS 140 Page Page 4545
Floating-Floating-PointPointArithmetiArithmeticcThere are There are four four arithmetic arithmetic operators operators for floating-for floating-point point numbers.numbers.+ Add+ Add
- Subtract- Subtract
* Multiply* Multiply
/ Divide/ Divide
//Example FloatArithmetic#include <iostream>using namespace std;
void main(){ double interestRate = 0.075; double balance = 278.93; double depositAmount = 309.14; double withdrawalAmount = 416.72; int daysUntilPayday = 19; double interestEarned; double dailyAllowance;
balance = balance + depositAmount - withdrawalAmount; interestEarned = interestRate * balance; balance = balance + interestEarned; dailyAllowance = balance / daysUntilPayday;
cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "Until payday, you\'ll have to\nget by on $" << dailyAllowance << " per day!" << endl << endl;
return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 4646
IntegerIntegerArithmetiArithmeticc
There are There are five five arithmetic arithmetic operators operators for integers.for integers.+ Add+ Add
- Subtract- Subtract
* Multiply* Multiply
/ Integer/ Integer DivideDivide
//Example IntegerArithmetic#include <iostream>using namespace std;
void main(){ const int PiecesPerLargePizza = 8; const int PiecesPerSmallPizza = 4;
int nbrOfLargePizzas; int nbrOfSmallPizzas; int nbrOfConsumers; int nbrOfPieces; int piecesPerConsumer; int nbrOfSparePieces;
cout << "How many large pizzas? "; cin >> nbrOfLargePizzas; cout << "How many small pizzas? "; cin >> nbrOfSmallPizzas; cout << "How many consumers? "; cin >> nbrOfConsumers;
nbrOfPieces = nbrOfLargePizzas * PiecesPerLargePizza + nbrOfSmallPizzas * PiecesPerSmallPizza; piecesPerConsumer = nbrOfPieces / nbrOfConsumers; nbrOfSparePieces = nbrOfPieces % nbrOfConsumers;
cout << "\nOn the average, " << piecesPerConsumer << " pieces each.\n" << "(with " << nbrOfSparePieces << " pieces left over!)" << endl << endl;
return;}
% Modulus% Modulus
Chapter 2Chapter 2CS 140CS 140 Page Page 4747
Arithmetic Precedence RulesArithmetic Precedence RulesWhen evaluating arithmetic expressions, C++ When evaluating arithmetic expressions, C++ uses specific uses specific precedence rulesprecedence rules to determine to determine which operators should be executed in which which operators should be executed in which order.order.• Parentheses take the highest precedenceParentheses take the highest precedence
• Multiplication, division, and modulus come Multiplication, division, and modulus come second.second.• Addition and subtraction take the lowest Addition and subtraction take the lowest precedence.precedence.• Precedence ties are handled in left-to-right Precedence ties are handled in left-to-right fashion.fashion.100 - 5 * 4 + 75 = 100 - 5 * 4 + 75 =
(100 - 5) * 4 + 75 = (100 - 5) * 4 + 75 =
100 - 5 * (4 + 75) = 100 - 5 * (4 + 75) =
95 * 4 + 75 = 95 * 4 + 75 =
100 - 5 * 79 = 100 - 5 * 79 =
80 + 75 = 80 + 75 =
380 + 75 = 380 + 75 =
155 155
455 455
-295-295
100 - 20 + 75 =100 - 20 + 75 =
100 - 395 =100 - 395 =
Chapter 2Chapter 2CS 140CS 140 Page Page 4848
Additional Assignment Additional Assignment OperatorsOperators
Certain shorthand operators can be used Certain shorthand operators can be used when a variable’s value is being altered by when a variable’s value is being altered by performing a simple operation on it.performing a simple operation on it.
value = value + otherValue;value = value + otherValue;
probability = probability / 100;probability = probability / 100;
x = x - y * z;x = x - y * z;
value += otherValue;value += otherValue;
probability /= 100;probability /= 100;
x -= y * z;x -= y * z;
dayOfYear = dayOfYear % 365;dayOfYear = dayOfYear % 365;
dayOfYear %= 365;dayOfYear %= 365;
salary = salary * 3.5;salary = salary * 3.5;
salary *= 3.5;salary *= 3.5;
Chapter 2Chapter 2CS 140CS 140 Page Page 4949
Increment and Decrement Increment and Decrement OperatorsOperators
Incrementing or decrementing a numerical Incrementing or decrementing a numerical value by one can be done with an even simpler value by one can be done with an even simpler mechanism.mechanism.
number = number + 1;number = number + 1; number++;number++; ++number;++number;
ctdown = ctdown - 1;ctdown = ctdown - 1; ctdown--;ctdown--; --ctdown;--ctdown;
//Example IncrementDecrement#include <iostream>using namespace std;
void main(){ int nbr = 57; cout << nbr << endl; cout << nbr++ << endl; cout << nbr << endl; cout << ++nbr << endl; cout << nbr << endl << endl; return;}
The order in The order in which the which the
increment or increment or decrement decrement operator is operator is applied will applied will determine determine
whether the whether the operation is operation is
applied before applied before or after a value or after a value
is returned.is returned.
Chapter 2Chapter 2CS 140CS 140 Page Page 5050
Pay total Pay total hours hours
worked at worked at regular rateregular rate
Pay 40 hours Pay 40 hours at regular at regular
rate & extra rate & extra hours at hours at
time-and-a-time-and-a-halfhalf
BranchingBranchingThere may be circumstances in a program when There may be circumstances in a program when the next step to perform depends on a particular the next step to perform depends on a particular condition.condition.
Did the hourly Did the hourly employee work employee work over 40 hours?over 40 hours?
Proceed Proceed to the to the next next
playerplayer
Increment the Increment the player’s player’s
winnings by the winnings by the dollar amount dollar amount
times the times the number of number of
occurrences of occurrences of the letterthe letter
Is the chosen Is the chosen WoF letter WoF letter
anywhere in the anywhere in the puzzle?puzzle?
Chapter 2Chapter 2CS 140CS 140 Page Page 5151
BranchingBranchingviavia if ifandand else else
In C++, simple In C++, simple branching is branching is done with done with ifif--else else statements.statements.
//Example SimpleIfElse// 1) Requests order amount, weight, in-state status// 2) Calculates discount rate for expensive orders// 3) Calculates shipping costs for all orders// 4) Calculates tax for in-state orders// 5) Outputs all results
#include <iostream>using namespace std;
void main(){ double orderAmt; double orderWeight; double discount; double shipping; char YorN; bool inState; double tax; double totalAmt;
cout << "Enter the total amount of the order: $"; cin >> orderAmt; if (orderAmt > 100.00) discount = 0.20; else discount = 0.00;
cout << "Enter the weight of the order (in pounds): "; cin >> orderWeight; if (orderWeight <= 1.0) shipping = 0.00; else shipping = 2.00 * orderWeight;
Branch is Branch is determined by a determined by a
boolean “greater-boolean “greater-than” operatorthan” operator
Branch is Branch is determined by determined by
a boolean a boolean “less-than-or-“less-than-or-
equal-to” equal-to” operatoroperator
Chapter 2Chapter 2CS 140CS 140 Page Page 5252
cout << "Is this an in-state order? Enter Y or N: "; cin >> yOrN; if ((yOrN == 'y') || (yOrN == 'Y')) inState = true; else inState = false;
if (inState) tax = 0.0675 * (orderAmt - discount * orderAmt); else tax = 0.00;
if ((discount > 0.0) && (!inState)) discount /= 2;
totalAmt = (orderAmt - discount * orderAmt) + tax + shipping; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << endl << endl << "Order: +$" << orderAmt << endl << "Discount: -$" << discount * orderAmt << endl << "Shipping: +$" << shipping << endl << "Tax: +$" << tax << endl << endl << "Total: $" << totalAmt << endl << endl;
return;}
Equality Equality and OR and OR
operatorsoperators
Boolean Boolean variable variable
is is examinedexamined
AND and AND and NOT NOT
operatorsoperators
Chapter 2Chapter 2CS 140CS 140 Page Page 5353
Another Another ifif--else else ExampleExampleBy using compound statements (enclosed in By using compound statements (enclosed in braces)braces) if if--else else statements can have more statements can have more complex branches.complex branches.//Example CompoundIfElse
#include <iostream>using namespace std;
void main(){ int favNbr, leastFavNbr;
cout << "Enter your favorite number: "; cin >> favNbr; if (favNbr == 7) { cout << "LUCKY NUMBER SEVEN!\n"; cout << "The odds are in your favor!" << endl << endl; } else cout << "What a risk-taker!" << endl << endl;
cout << "Enter your least favorite number: "; cin >> leastFavNbr; if (leastFavNbr = 13) { cout << "SILLY SUPERSTITION!" << endl; cout << "Grow up, already!" << endl << endl << endl; } else { cout << "Too bad!\n"; cout << "I was just about to give you " << leastFavNbr << " dollars!" << endl << endl << endl; cout << "Oh, well. Maybe next time..." << endl << endl << endl; }
return;}
Because the assignment operator was used
instead of the equality operator!
Why did this
happen?
Chapter 2Chapter 2CS 140CS 140 Page Page 5454
One More One More ifif--else else ExampleExample//Example NestedIfElse#include <iostream>using namespace std;
void main(){ int month, year, payday1, payday2;
cout << "Enter an integer representing” << " the month: "; cin >> month; cout << "Enter the four-digit year: "; cin >> year;
if ((month == 2) && (year % 4 != 0)) payday1 = 14; else payday1 = 15;
if (month == 2) { if (year % 4 == 0) payday2 = 29; else payday2 = 28; } else { if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) payday2 = 30; else payday2 = 31; }
cout << "This month's paydays are on " << month << '/' << payday1 << '/' << (year % 100) << " and " << month << '/' << payday2 << '/' << (year % 100) << ".\n\n";
return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 5555
LoopingLoopingThere may be circumstances in a program There may be circumstances in a program when a certain step should be repeated until when a certain step should be repeated until a particular condition is true.a particular condition is true.
Request Request another another
letter from letter from the userthe user
Has the Has the user user
entered the entered the letter ‘Y’ or letter ‘Y’ or
‘N’ yet?‘N’ yet?
Proceed Proceed with the with the
rest of the rest of the programprogram
Chapter 2Chapter 2CS 140CS 140 Page Page 5656
BranchingBranchingviavia while while
In C++, simple In C++, simple looping may be done looping may be done withwith while while statements.statements.//Example WhileLoop
#include <iostream>using namespace std;
void main(){ char isItPerishable; int nbrDaysUntilExpire = 90;
cout << "Is the product perishable? " << "(Enter Y or N) "; cin >> isItPerishable; while ((isItPerishable != 'Y') && (isItPerishable != 'y') && (isItPerishable != 'N') && (isItPerishable != 'n')) { cout << "Invalid response. " << "Enter Y or N: "; cin >> isItPerishable; }
if ((isItPerishable == 'Y') || (isItPerishable == 'y')) { cout << "Enter the number of " << "days until the product expires: "; cin >> nbrDaysUntilExpire; while (nbrDaysUntilExpire <= 0) { cout << "Invalid response. " << "Enter a positive number: "; cin >> nbrDaysUntilExpire; } }
cout << endl << "The product expires in " << nbrDaysUntilExpire << " days." << endl << endl;
return;}
Chapter 2Chapter 2CS 140CS 140 Page Page 5757
//Example CountingTotalingLoop#include <iostream>using namespace std;
void main(){ int receiptCount = 0; double receiptTotal = 0.00; double receiptAmount; double receiptMean;
cout << "Enter the amount of each receipt." << endl; cout << "When finished, enter -1." << endl << endl; cout << '$'; cin >> receiptAmount; while (receiptAmount >= 0.00) { receiptCount++; receiptTotal += receiptAmount; cout << '$'; cin >> receiptAmount; } receiptMean = receiptTotal / receiptCount;
cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << endl << endl << "Average receipt amount: $" << receiptMean << endl << endl;
return;}
Counting Counting and and Totaling Totaling with Loopswith Loops
Chapter 2Chapter 2CS 140CS 140 Page Page 5858
Branching viaBranching via do-while do-whileWith aWith a while while statement, the loop condition is statement, the loop condition is checked before executing the loop contents, checked before executing the loop contents, making it possible to making it possible to nevernever execute those execute those contents.contents.
If the algorithm calls for executing the contents If the algorithm calls for executing the contents at least once, then it might be better to use aat least once, then it might be better to use a do-while do-while statement, which checks the loop statement, which checks the loop condition condition afterafter executing the loop contents. executing the loop contents.
check condition
execute contentsexecute contents check condition
execute contentsexecute contents
Chapter 2Chapter 2CS 140CS 140 Page Page 5959
//Example DoWhileLoop#include <iostream>using namespace std;
void main(){ int favoriteNumber;
do { cout << "Enter your favorite number: "; cin >> favoriteNumber; } while (favoriteNumber != 13);
cout << endl << "13! Why, that\'s my favorite number, too!\n\n";
return;}
A SimpleA Simple do-while do-while ExampleExample
Chapter 2Chapter 2CS 140CS 140 Page Page 6060
//Example InfiniteLoop#include <iostream>using namespace std;
void main(){ int value; int guessedValue;
cout << "Enter a value: "; cin >> value;
guessedValue = 0; while (value != guessedValue) cout << guessedValue++ << endl;
cout << "\nWOO HOO!!! The computer\nFINALLY " << "guessed your value: " << value << "!\n\n";
return;}
Infinite Infinite LoopsLoopsOne danger with looping is the One danger with looping is the prospect of generating an prospect of generating an infiniteinfinite loop, whose exit condition is loop, whose exit condition is nevernever met. met.
This This condition condition
might might nevernever be true!be true!
Chapter 7Chapter 7More Flow of ControlMore Flow of ControlGoals:Goals:
• To analyze the use of Boolean expressionsTo analyze the use of Boolean expressions
• To introduce the notion of enumerated typesTo introduce the notion of enumerated types
• To explore theTo explore the switch switch statement as an alternative statement as an alternative to multiwayto multiway if-else if-else statementsstatements
• To examine theTo examine the for for-statement as a looping option-statement as a looping option
• To demonstrate the design of good nested loopsTo demonstrate the design of good nested loops
• To view the conditional statement as an alternative To view the conditional statement as an alternative to a simpleto a simple if-else if-else statementstatement
Chapter 7Chapter 7CS 140CS 140 Page Page 6262
Precedence Rules for Boolean Precedence Rules for Boolean ExpressionsExpressions
With the addition of Boolean operators, With the addition of Boolean operators, the precedence rules that C++ uses to the precedence rules that C++ uses to evaluate expressions become more evaluate expressions become more complex.complex.• Parentheses still take the highest precedenceParentheses still take the highest precedence
• Multiplication, division, and modulus come second.Multiplication, division, and modulus come second.• Addition and subtraction take the next precedence.Addition and subtraction take the next precedence.
• Precedence ties are still handled in left-to-right Precedence ties are still handled in left-to-right fashion.fashion.
• Order-related inequality operators (<, >, <=, >=) are Order-related inequality operators (<, >, <=, >=) are next.next.• The pure equality/inequality (==, !=) operators are The pure equality/inequality (==, !=) operators are next.next.• The Boolean AND operator (&&) takes the next The Boolean AND operator (&&) takes the next precedence.precedence.• The Boolean OR operator (||) takes the lowest The Boolean OR operator (||) takes the lowest precedence.precedence.
Chapter 7Chapter 7CS 140CS 140 Page Page 6363
Precedence Rules ExamplesPrecedence Rules Examplesint x = 7,int x = 7, y = 7,y = 7, z = 7;z = 7;if (x == y == z)if (x == y == z) cout << “YES”;cout << “YES”;elseelse cout << “NO”;cout << “NO”;
int a = 5,int a = 5, b = 4,b = 4, c = 3;c = 3;if (a < b < c)if (a < b < c) cout << “YES”;cout << “YES”;elseelse cout << “NO”;cout << “NO”;
Output: NOOutput: NO
The left equality is The left equality is checked and evaluates checked and evaluates to true (numerical 1), to true (numerical 1), which is which is notnot equal to equal to
the z-value!the z-value!
Output: NOOutput: NO
The left equality is The left equality is checked and evaluates checked and evaluates to true (numerical 1), to true (numerical 1), which is which is notnot equal to equal to
the z-value!the z-value!
Output: YESOutput: YES
The left inequality is The left inequality is checked and evaluates checked and evaluates to false (numerical 0), to false (numerical 0),
which which isis less than the c- less than the c-value!value!
Output: YESOutput: YES
The left inequality is The left inequality is checked and evaluates checked and evaluates to false (numerical 0), to false (numerical 0),
which which isis less than the c- less than the c-value!value!
Chapter 7Chapter 7CS 140CS 140 Page Page 6464
Boolean Expressions -Boolean Expressions -Short-Circuit Evaluation of Short-Circuit Evaluation of &&&&When a Boolean expression using theWhen a Boolean expression using the && && operator is evaluated, the first subexpression is operator is evaluated, the first subexpression is evaluated first. If it evaluates toevaluated first. If it evaluates to falsefalse, then , then the second subexpression is the second subexpression is ignoredignored..
if ((x != 0) && (y/x > 1))if ((x != 0) && (y/x > 1)) z = 100;z = 100;elseelse z = -1;z = -1;
if ((y/x > 1) && (x != 0))if ((y/x > 1) && (x != 0)) z = 100;z = 100;elseelse z = -1;z = -1;
When this code When this code segment is segment is
encountered and x’s encountered and x’s value is zero, z will be value is zero, z will be
assigned either the assigned either the value 100 or the value value 100 or the value
-1.-1.When this code segment When this code segment is encountered and x’s is encountered and x’s
value is zero, the value is zero, the program crashes due to program crashes due to the attempt to divide by the attempt to divide by
zero!zero!
Chapter 7Chapter 7CS 140CS 140 Page Page 6565
Boolean Expressions -Boolean Expressions -Short-Circuit Evaluation of ||Short-Circuit Evaluation of ||When a Boolean expression using theWhen a Boolean expression using the || || operator is evaluated, the first subexpression operator is evaluated, the first subexpression is evaluated first. If it evaluates tois evaluated first. If it evaluates to truetrue, then , then the second subexpression is the second subexpression is ignoredignored..
if ((ct == 0) || (total/ct > 70))if ((ct == 0) || (total/ct > 70)) cout << “NO PROBLEMO”;cout << “NO PROBLEMO”;
if ((total/ct > 70) || (ct == 0))if ((total/ct > 70) || (ct == 0)) cout << “NO PROBLEMO”;cout << “NO PROBLEMO”;
When this code When this code segment is segment is
encountered encountered and ct’s value is and ct’s value is
zero, the zero, the message is message is
output.output.
When this code When this code segment is segment is
encountered and encountered and ct’s value is ct’s value is
zero, the zero, the program crashes program crashes
due to the due to the attempt to divide attempt to divide
by zero!by zero!
Chapter 7Chapter 7CS 140CS 140 Page Page 6666
Enumerated Enumerated TypesTypes
To enhance the readability of one’s code, a To enhance the readability of one’s code, a programmer can define an programmer can define an enumerated enumerated typetype, which consists of a set of integer , which consists of a set of integer constants.constants.// Example EnumeratedTypes
// This program uses enumerated types to cycle through the months of the year,
// processing a running total of monetary values for each month, followed by
// the cumulative total for the year.
//
// Note that the daily values are assumed to exist in an external file named
// GrossFile.txt, which must be in the project folder.
#include <iostream>
#include <fstream> // NEW: Allows access to external files.
using namespace std;
// Define a new type of variables, a subset of the integers.
enum MonthNumber { JANUARY = 1, FEBRUARY, MARCH, APRIL,
MAY, JUNE, JULY, AUGUST,
SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER };
Chapter 7Chapter 7CS 140CS 140 Page Page 6767
void main()
{
MonthNumber month;
double monthlyGross;
double totalGross = 0.0;
int monthLength;
int year;
int day;
bool leapYear;
double dailyGross;
// Declare an input file variable to make it possible
// to retrieve data from an external file, rather than
// force the user to respond to hundreds of queries.
// (We'll see this in more detail in Chapter 5!)
ifstream grossFile;
grossFile.open("GrossFile.txt");
// Format the common output to look like dollars and cents.
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
Chapter 7Chapter 7CS 140CS 140 Page Page 6868
// Query the user for the year in order to determine
// whether the year has 365 or 366 days.
cout << "What is the year in question? ";
cin >> year;
leapYear = ((year % 4 != 0) ||
((year % 100 == 0) && (year % 400 != 0)));
cout << endl;
// Loop through the year's twelve months, totaling the
// daily amounts retrieved from the external file.
month = JANUARY;
while (month <= DECEMBER)
{
// Determine the number of days in the current month.
if (month == FEBRUARY)
if (leapYear)
monthLength = 29;
else
monthLength = 28;
else if ((month == APRIL) || (month == JUNE) ||
(month == SEPTEMBER) || (month == NOVEMBER))
monthLength = 30;
else
monthLength = 31;
Chapter 7Chapter 7CS 140CS 140 Page Page 6969
// Loop through the current month's days and keep
// a running total of that month's daily values
// that are retrieved from the external file.
monthlyGross = 0.0;
day = 1;
while (day <= monthLength)
{
grossFile >> dailyGross;
monthlyGross += dailyGross;
day++;
}
// Output the current month's total.
cout << "The gross for month #";
if (month < OCTOBER)
cout << " ";
cout << month << " is $" << monthlyGross << endl;
// Add the month's total to the running total for the entire year.
totalGross += monthlyGross;
// Proceed to the next month.
month = MonthNumber(month + 1);
}
Chapter 7Chapter 7CS 140CS 140 Page Page 7070
// Close the external input file.
grossFile.close();
// Output the year's total.
cout << endl << "Total for year " << year
<< ": $" << totalGross << endl << endl;
return;
}
804.89 692.45 614.39 760.26 541.53 229.55 954.82 206.73 730.13 685.33 405.49 351.50 152.51 606.81 198.79 127.55 804.89 692.45 614.39 760.26 541.53 229.55 954.82 206.73 730.13 685.33 405.49 351.50 152.51 606.81 198.79 127.55 869.49 382.64 605.27 263.36 124.58 544.82 291.35 822.71 987.64 550.15 537.19 363.20 141.80 432.30 843.20 229.25 869.49 382.64 605.27 263.36 124.58 544.82 291.35 822.71 987.64 550.15 537.19 363.20 141.80 432.30 843.20 229.25 766.33 964.90 803.19 845.54 819.56 226.56 171.96 726.15 173.52 207.94 306.04 365.12 305.00 652.27 705.38 124.09 766.33 964.90 803.19 845.54 819.56 226.56 171.96 726.15 173.52 207.94 306.04 365.12 305.00 652.27 705.38 124.09 394.89 969.18 133.97 582.64 439.77 912.91 547.71 767.07 828.21 165.28 807.91 922.96 885.58 114.42 907.91 747.27 394.89 969.18 133.97 582.64 439.77 912.91 547.71 767.07 828.21 165.28 807.91 922.96 885.58 114.42 907.91 747.27 239.85 769.38 991.46 645.89 112.00 601.68 590.91 531.67 283.88 354.00 363.00 129.22 546.80 607.22 950.95 701.57 239.85 769.38 991.46 645.89 112.00 601.68 590.91 531.67 283.88 354.00 363.00 129.22 546.80 607.22 950.95 701.57 583.82 445.84 350.40 464.60 788.99 512.66 607.69 704.70 676.68 693.55 928.43 465.61 984.07 222.49 624.66 419.50 583.82 445.84 350.40 464.60 788.99 512.66 607.69 704.70 676.68 693.55 928.43 465.61 984.07 222.49 624.66 419.50 719.75 347.79 678.47 988.55 662.02 250.32 350.43 932.13 959.49 753.67 110.79 365.61 737.57 217.85 121.83 926.01 719.75 347.79 678.47 988.55 662.02 250.32 350.43 932.13 959.49 753.67 110.79 365.61 737.57 217.85 121.83 926.01 863.44 756.00 149.19 750.56 673.25 166.11 930.27 383.58 614.17 316.75 278.47 177.01 704.67 179.26 150.18 800.91 863.44 756.00 149.19 750.56 673.25 166.11 930.27 383.58 614.17 316.75 278.47 177.01 704.67 179.26 150.18 800.91 466.05 645.18 854.05 928.95 128.43 121.07 429.77 114.67 664.27 840.35 574.38 924.22 652.51 383.49 244.99 341.42 466.05 645.18 854.05 928.95 128.43 121.07 429.77 114.67 664.27 840.35 574.38 924.22 652.51 383.49 244.99 341.42 126.59 946.36 815.44 510.02 409.20 948.28 315.16 929.74 187.37 619.77 628.32 371.11 230.43 560.67 681.65 324.64 126.59 946.36 815.44 510.02 409.20 948.28 315.16 929.74 187.37 619.77 628.32 371.11 230.43 560.67 681.65 324.64 804.34 609.70 398.74 450.59 585.69 515.57 148.97 344.36 927.68 750.45 669.46 783.11 882.45 456.66 788.03 770.01 804.34 609.70 398.74 450.59 585.69 515.57 148.97 344.36 927.68 750.45 669.46 783.11 882.45 456.66 788.03 770.01 331.61 766.63 625.02 640.51 229.06 587.56 402.53 347.51 208.60 290.61 738.95 490.06 559.96 395.72 857.07 601.90 331.61 766.63 625.02 640.51 229.06 587.56 402.53 347.51 208.60 290.61 738.95 490.06 559.96 395.72 857.07 601.90 725.90 792.64 583.58 465.12 423.84 188.66 768.50 764.49 944.91 423.56 802.31 748.45 133.92 942.87 459.21 912.06 725.90 792.64 583.58 465.12 423.84 188.66 768.50 764.49 944.91 423.56 802.31 748.45 133.92 942.87 459.21 912.06 202.64 669.65 244.36 267.78 280.69 665.23 273.30 719.14 955.75 520.38 861.99 904.06 807.55 766.58 354.98 122.16 202.64 669.65 244.36 267.78 280.69 665.23 273.30 719.14 955.75 520.38 861.99 904.06 807.55 766.58 354.98 122.16 487.56 648.48 570.39 112.33 648.59 848.26 989.62 996.48 276.74 502.36 169.84 754.52 628.92 800.93 807.36 846.09 487.56 648.48 570.39 112.33 648.59 848.26 989.62 996.48 276.74 502.36 169.84 754.52 628.92 800.93 807.36 846.09 629.28 911.40 930.46 345.62 627.60 315.82 948.97 105.19 372.54 503.41 939.60 211.56 903.16 308.51 794.48 552.82 629.28 911.40 930.46 345.62 627.60 315.82 948.97 105.19 372.54 503.41 939.60 211.56 903.16 308.51 794.48 552.82 711.78 334.69 111.51 360.07 381.24 855.45 554.16 239.93 649.52 532.68 359.52 763.75 905.22 142.65 821.94 228.62 711.78 334.69 111.51 360.07 381.24 855.45 554.16 239.93 649.52 532.68 359.52 763.75 905.22 142.65 821.94 228.62 166.90 651.00 931.04 956.00 348.97 726.92 891.71 644.16 368.09 137.02 604.67 638.97 692.28 609.94 335.46 439.60 166.90 651.00 931.04 956.00 348.97 726.92 891.71 644.16 368.09 137.02 604.67 638.97 692.28 609.94 335.46 439.60 586.73 711.97 449.90 404.37 458.75 624.42 244.52 872.43 555.26 763.47 849.55 766.74 316.18 232.93 533.12 994.29 586.73 711.97 449.90 404.37 458.75 624.42 244.52 872.43 555.26 763.47 849.55 766.74 316.18 232.93 533.12 994.29 436.36 650.67 884.43 409.04 239.49 639.30 504.23 452.87 517.19 921.75 980.61 840.92 836.06 812.39 878.22 606.18 436.36 650.67 884.43 409.04 239.49 639.30 504.23 452.87 517.19 921.75 980.61 840.92 836.06 812.39 878.22 606.18 566.11 644.11 719.23 369.43 733.64 822.44 983.80 349.79 651.63 346.83 808.68 782.12 830.73 789.92 111.56 156.06 566.11 644.11 719.23 369.43 733.64 822.44 983.80 349.79 651.63 346.83 808.68 782.12 830.73 789.92 111.56 156.06 724.22 575.78 219.53 642.90 109.59 846.83 329.96 826.12 760.37 561.27 181.54 400.16 111.32 310.52 863.88 554.52 724.22 575.78 219.53 642.90 109.59 846.83 329.96 826.12 760.37 561.27 181.54 400.16 111.32 310.52 863.88 554.52 569.27 598.05 643.70 407.44 974.13 569.98 235.70 205.93 161.91 937.90 896.32 856.69 733.53 698.02569.27 598.05 643.70 407.44 974.13 569.98 235.70 205.93 161.91 937.90 896.32 856.69 733.53 698.02
Chapter 7Chapter 7CS 140CS 140 Page Page 7171
switchswitch StatementsStatements
C++C++ switch switch statements provide a simple statements provide a simple alternative to the use of convoluted nestedalternative to the use of convoluted nested if- if-else else statements.statements.if (month == 2)if (month == 2){{ if (leapYear)if (leapYear) daysInMonth = 29;daysInMonth = 29; elseelse daysInMonth = 28;daysInMonth = 28;}}else if ((month == 4) ||else if ((month == 4) || (month == 6) ||(month == 6) || (month == 9) ||(month == 9) || (month == 11)) (month == 11)) daysInMonth = 30;daysInMonth = 30;elseelse daysInMonth = 31;daysInMonth = 31;
switch (month)switch (month){{ case 2: {case 2: { if (leapYear)if (leapYear) daysInMonth = 29;daysInMonth = 29; elseelse daysInMonth = 28;daysInMonth = 28; break;break; }} case 4:case 4: case 6:case 6: case 9:case 9: case 11: { daysInMonth = 30; break; } case 11: { daysInMonth = 30; break; } default: { daysInMonth = 31; break; }default: { daysInMonth = 31; break; }}}
Chapter 7Chapter 7CS 140CS 140 Page Page 7272
Conditional StatementsConditional StatementsC++ conditional statements provide a C++ conditional statements provide a concise alternative to the use of relatively concise alternative to the use of relatively simplesimple if-else if-else statements.statements.
if (leapYear)if (leapYear) daysInMonth = 29;daysInMonth = 29;elseelse daysInMonth = 28;daysInMonth = 28;
daysInMonth = (leapYear) ? 29 : 28;daysInMonth = (leapYear) ? 29 : 28;
if (value > 0)if (value > 0) cout << “GOOD”;cout << “GOOD”;elseelse cout << “BAD”;cout << “BAD”;
(value > 0) ? (cout << “GOOD”) : (cout << “BAD);(value > 0) ? (cout << “GOOD”) : (cout << “BAD);
Chapter 7Chapter 7CS 140CS 140 Page Page 7373
// Example SwitchStatements
// This program simulates a motel's pay-per-view movie
// channel, querying the user regarding desired movie
// type, and then regarding desired movie. The program
// finally outputs the charge that will be levied to
// the user if the selected movie is actually viewed.
#include <iostream>
using namespace std;
void outputClassicFilmsHeader(); // NEW: Programmer-defined
void outputActionMovieHeader(); // functions. We'll see
void outputScienceFictionHeader(); // this in more detail in
void outputChildrensMoviesHeader(); // Chapters 3 and 4.
void outputForeignFilmsHeader();
void main()
{
char movieChoice;
int movieType;
bool typeSelected;
// Loop until the user selects a movie or quits.
do
{
typeSelected = false;
cout << "Welcome to the Lackluster Movie Channel!" << endl;
cout << "Available ONLY at the Bates Family Motel!" << endl << endl;
Chapter 7Chapter 7CS 140CS 140 Page Page 7474
// Loop until the user picks a movie type or quits.
while (!typeSelected)
{
cout << "Enter the number corresponding to your "
<< "desired movie type." << endl << endl;
cout << " 1 - Classic Films" << endl
<< " 2 - Action Movies" << endl
<< " 3 - Science Fiction" << endl
<< " 4 - Children's Movies" << endl
<< " 5 - Foreign Films" << endl << endl
<< " 0 - Quit" << endl << endl
<< "Enter number here: ";
cin >> movieType;
cout << endl;
typeSelected = ((movieType >= 0) && (movieType <= 5));
}
// List the movie selections of the chosen type.
switch(movieType)
{
case(1): { outputClassicFilmsHeader(); break; }
case(2): { outputActionMovieHeader(); break; }
case(3): { outputScienceFictionHeader(); break; }
case(4): { outputChildrensMoviesHeader(); break; }
case(5): { outputForeignFilmsHeader(); break; }
}
The break The break statements statements
ensure that the ensure that the switch switch
statement is statement is exited once the exited once the
appropriate appropriate case is handled.case is handled.
Without the Without the break break
statements, statements, multiple multiple
functions might functions might be called.be called.
Chapter 7Chapter 7CS 140CS 140 Page Page 7575
// Query the user for a specific movie, unless the user
// selected "Quit", in which case, prepare to do so.
switch(movieType)
{
case(1):
case(2):
case(3):
case(4):
case(5): {
cout << "\tEnter letter here: ";
cin >> movieChoice;
break;
}
default: { movieChoice = 'Q'; break;}
}
When several cases warrant the When several cases warrant the same actions, the code only same actions, the code only
needs to appear once, with no needs to appear once, with no break statements separating the break statements separating the
cases.cases.
The default case is executed if no The default case is executed if no other case value matches.other case value matches.
It doesn’t It doesn’t needneed a break statement a break statement at the end, but using one enhances at the end, but using one enhances
readability and modifiability.readability and modifiability.
Chapter 7Chapter 7CS 140CS 140 Page Page 7676
// Determine charge based upon movie selection.
switch(movieChoice)
{
case('B'):
case('b'): {
((movieType == 1) || (movieType == 5)) ?
(cout << "\tCharge: $6.00"):
(cout << "\tCharge: $3.50");
break;
}
case('C'):
case('c'): {
(movieType == 4) ?
(cout << "\tCharge: $6.00"):
(cout << "\tCharge: $3.50");
break;
}
case('A'):
case('a'):
case('D'):
case('d'):
case('E'):
case('e'): { cout << "\tCharge: $3.50"; break; }
case('R'):
case('r'): { movieType = -1; break; }
default: { cout << "\tNo movie ordered. No charge."; break; }
}
Conditional statements Conditional statements enhance the enhance the
readability of the code readability of the code when used to replace when used to replace relatively short if-else relatively short if-else
statements.statements.
Any Boolean Any Boolean expression is expression is
permissible in a permissible in a conditional statement.conditional statement.
Chapter 7Chapter 7CS 140CS 140 Page Page 7777
if (movieType >= 0)
cout << endl << endl << "Enjoy your stay at the Bates Motel!";
cout << endl << endl;
}
while (movieType < 0);
return;
}
// List the "classic" film choices.
void outputClassicFilmsHeader()
{
cout << "\tEnter the letter corresponding to the film you wish to see." << endl;
cout << "\t A - \"American Pie\"" << endl
<< "\t B - \"Animal House\"" << endl
<< "\t C - \"Caddyshack\"" << endl
<< "\t D - \"Police Academy\"" << endl
<< "\t E - \"Porky\'s\"" << endl << endl
<< "\t Q - Quit" << endl
<< "\t R - Return to Main Menu" << endl << endl;
return;
}
Chapter 7Chapter 7CS 140CS 140 Page Page 7878
// List the "action" movie choices.
void outputActionMovieHeader()
{
cout << "\tEnter the letter corresponding to the film you wish to see." << endl;
cout << "\t A - \"Action Jackson\"" << endl
<< "\t B - \"A Civil Action\"" << endl
<< "\t C - \"Executive Action\"" << endl
<< "\t D - \"The Last Action Hero\"" << endl
<< "\t E - \"Missing In Action\"" << endl << endl
<< "\t Q - Quit" << endl
<< "\t R - Return to Main Menu" << endl << endl;
return;
}
// List the "science" fiction choices.
void outputScienceFictionHeader()
{
cout << "\tEnter the letter corresponding to the film you wish to see." << endl;
cout << "\t A - \"Anatomy Of A Murder\"" << endl
<< "\t B - \"Bio-Dome\"" << endl
<< "\t C - \"Botany Bay\"" << endl
<< "\t D - \"The Mechanic\"" << endl
<< "\t E - \"Weird Science\"" << endl << endl
<< "\t Q - Quit" << endl
<< "\t R - Return to Main Menu" << endl << endl;
return;
}
Chapter 7Chapter 7CS 140CS 140 Page Page 7979
// List the "children's" movie choices.
void outputChildrensMoviesHeader()
{
cout << "\tEnter the letter corresponding to the film you wish to see." << endl;
cout << "\t A - \"The Bad Seed\"" << endl
<< "\t B - \"Children Of The Corn\"" << endl
<< "\t C - \"The Exorcist\"" << endl
<< "\t D - \"The Omen\"" << endl
<< "\t E - \"Rosemary\'s Baby\"" << endl << endl
<< "\t Q - Quit" << endl
<< "\t R - Return to Main Menu" << endl << endl;
return;
}
// List the "foreign" film choices.
void outputForeignFilmsHeader()
{
cout << "\tEnter the letter corresponding to the film you wish to see." << endl;
cout << "\t A - \"Amazon Women On The Moon\"" << endl
<< "\t B - \"The French Connection\"" << endl
<< "\t C - \"The Manchurian Candidate\"" << endl
<< "\t D - \"My Big Fat Greek Wedding\"" << endl
<< "\t E - \"The Spanish Prisoner\"" << endl << endl
<< "\t Q - Quit" << endl
<< "\t R - Return to Main Menu" << endl << endl;
return;
}
Chapter 7Chapter 7CS 140CS 140 Page Page 8080
Chapter 7Chapter 7CS 140CS 140 Page Page 8181
TheThe for for StatementStatementThe C++The C++ for for statement is designed to facilitate statement is designed to facilitate looping when the control of the loop contains looping when the control of the loop contains three standard features:three standard features:
• An initialization action that is performed just An initialization action that is performed just before the loop is started the first time.before the loop is started the first time.
• A Boolean expression that is checked just A Boolean expression that is checked just before entering the loop at each iteration.before entering the loop at each iteration.
• An update action that is performed just after An update action that is performed just after each iteration of the loop is completed.each iteration of the loop is completed.
for (for (initActioninitAction; ; booleanExpbooleanExp; ; updateActionupdateAction)) bodyOfLoopbodyOfLoop
Chapter 7Chapter 7CS 140CS 140 Page Page 8282
// Example ForLoopEnumerated// This program uses an enumerated type to demonstrate the use of the for// statement in a loop structure. It queries the user for the number of// hour worked in a guven week, and then calculates the resulting minimum// wage pay, assuming that the worker receives time-and-a-half on Sundays.
#include <iostream>using namespace std;
enum Day { SUNDAY = 1, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
// Global constants, defined before the main function in case the program is// ever modified to have additional functions that might need these values.const double PAY_RATE = 5.15;const double OVERTIME_FACTOR = 1.5;
void main(){ Day dayOfWeek; double hoursWorked; double payForWeek = 0.0;
for (dayOfWeek = SUNDAY; dayOfWeek <= SATURDAY; dayOfWeek = Day(dayOfWeek +1))
AA for for-loop Example-loop Example
dayOfWeek is dayOfWeek is initialized to SUNDAY initialized to SUNDAY when the for-loop is when the for-loop is first encountered.first encountered.
This inequality is checked This inequality is checked just before the body of the just before the body of the
loop is entered (or re-loop is entered (or re-entered).entered).
This assignment statement is This assignment statement is executed right after each executed right after each
execution of the body of the execution of the body of the loop.loop.
Chapter 7Chapter 7CS 140CS 140 Page Page 8383
{ // Query the user regarding each day's hours worked. cout << "Enter the hours worked on "; switch (dayOfWeek) { case SUNDAY: cout << "Sunday: "; break; case MONDAY: cout << "Monday: "; break; case TUESDAY: cout << "Tuesday: "; break; case WEDNESDAY: cout << "Wednesday: "; break; case THURSDAY: cout << "Thursday: "; break; case FRIDAY: cout << "Friday: "; break; case SATURDAY: cout << "Saturday: "; break; } cin >> hoursWorked;
// Calculate the day's pay and add to the running total. (dayOfWeek == SUNDAY) ? (payForWeek += OVERTIME_FACTOR * hoursWorked * PAY_RATE) : (payForWeek += hoursWorked * PAY_RATE); }
// Output the weekly pay, formatted as dollars and cents. cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << endl << endl << "Your Pay For The Week Is $” << payForWeek << endl << endl;
return;}
Chapter 7Chapter 7CS 140CS 140 Page Page 8484
// Example ForLoopDecrements// This program queries the user regarding the U.S. presidential// elections between 1920 and 2000, tallying the number of times// that Democrats or Republicans won, and reporting the results.#include <iostream>using namespace std;
void main(){ char party; int electionYear; int elephants = 0; int donkeys = 0;
// Loop through the election years // in reverse numerical order. for (electionYear = 2000; electionYear >= 1924; electionYear -= 4) { cout << "Which party won in " << electionYear << "? (Enter R or D) "; cin >> party; (party == 'R') ? elephants++ : donkeys++; } (elephants > donkeys) ? (cout << "\nRepublicans Rule!\n\n") : ((donkeys > elephants) ? (cout << "\nDemocrats Dominate!\n\n") : (cout << "\nTiebreaker Time!\n\n"));
return;}
AnotherAnother forfor-loop -loop ExampleExample
Chapter 7Chapter 7CS 140CS 140 Page Page 8585
// Evample NestedForLoops// This program uses nested for loops to display an "animated" message.
#include <iostream>using namespace std;
void main(){ int iterationNbr, repetitionNbr, indentSpaceNbr; cout << endl;
// Use iterationNbr to index how many "frames" in the "animation". for (iterationNbr = 1; iterationNbr <= 25; iterationNbr++)
// Print the exact same line repetitionNbr times, to give // the user a chance to read it before it "moves". for (repetitionNbr = 1; repetitionNbr <= 100; repetitionNbr++) { cout << '\r';
// Preface the message with iterationNbr blank spaces. for (indentSpaceNbr = 1; indentSpaceNbr <= iterationNbr; indentSpaceNbr++) cout << ' ';
cout << "HAPPY NEW YEAR!"; } cout << endl << endl;
return;}
NestedNested for for-loops-loops
Chapter 7Chapter 7CS 140CS 140 Page Page 8686
// Example ForLoopCalendar// This program queries the user for a month a year// and then uses for loops to generate and output a// calendar for that month in that year.
#include <iostream>#include <iomanip> // Permits output manipulation.using namespace std;
void main(){ int userYear; // User-specified year. int userMonth; // User-specified month. int day; // Variable to cycle through month's days. int month; // Variable to cycle through year's months. int nbrRows; // Number of rows in display calendar. int nbrColumns; // Number of columns in display calendar. int row; // Variable to cycle through calendar rows. int column; // Variable to cycle through calendar columns. int nbrDaysInMonth; // Number of days in user-specified month. int firstDayOfYear; // First day of week of user-specified year. int firstDayOfMonth; // First day of week for user-specified month.
A More ElaborateA More Elaborate for for-loop -loop ExampleExample
Chapter 7Chapter 7CS 140CS 140 Page Page 8787
// Request the month from the user and error-check it.
cout << "Enter the month of the calendar to be generated: ";
cin >> userMonth;
for ( ; ((userMonth <= 0) || (userMonth > 12)) ; )
{
cout << "\nYou must enter a number between 1 and 12 for the month.\n"
<< "Enter the month of the calendar to be generated: ";
cin >> userMonth;
}
// Request the year from the user and error-check it.
// (Note that the formula used in this algorithm depennds
// on the year being in the range from 1900 to 2100.)
cout << "\nEnter the year of the calendar to be generated: ";
cin >> userYear;
for ( ; ((userYear < 1900) || (userYear > 2100)) ; )
{
cout << "\nThis program only works for the 20th and 21st centuries!.\n\n"
<< "Enter the year of the calendar to be generated: ";
cin >> userYear;
}
Notice that theseNotice that these for for loops loops perform perform nono initialization initialization actions and actions and nono update update
actions!actions!
Chapter 7Chapter 7CS 140CS 140 Page Page 8888
// This formula determines the day of the week on
// which year begins (1 = Sunday, 2 = Monday, etc.)
firstDayOfYear = (((userYear + 3)/4) + userYear + 5) % 7 + 1;
// This loop determines both the number of days in the user-specified
// month and the day of the week on which that month begins.
firstDayOfMonth = firstDayOfYear;
for (month = 1; month <= userMonth; month++)
{
switch (month)
{
case (2): { nbrDaysInMonth = (userYear % 4 == 0) ? (29) : (28); break; }
case (4):
case (6):
case (9):
case (11): { nbrDaysInMonth = 30; break; }
default: { nbrDaysInMonth = 31; break; }
}
firstDayOfMonth = (month < userMonth) ?
(firstDayOfMonth + nbrDaysInMonth) :
((firstDayOfMonth - 1) % 7 + 1);
}
Chapter 7Chapter 7CS 140CS 140 Page Page 8989
// Output the calendar header, identifying the month and
// year, as well as the labels for the days of the week.
cout << endl << endl;
switch (userMonth)
{
case 1: { cout << setw(17)<< "JANUARY "; break; }
case 2: { cout << setw(18)<< "FEBRUARY "; break; }
case 3: { cout << setw(16)<< "MARCH "; break; }
case 4: { cout << setw(16)<< "APRIL "; break; }
case 5: { cout << setw(15)<< "MAY "; break; }
case 6: { cout << setw(16)<< "JUNE "; break; }
case 7: { cout << setw(16)<< "JULY "; break; }
case 8: { cout << setw(17)<< "AUGUST "; break; }
case 9: { cout << setw(18)<< "SEPTEMBER "; break; }
case 10: { cout << setw(17)<< "OCTOBER "; break; }
case 11: { cout << setw(18)<< "NOVEMBER "; break; }
case 12: { cout << setw(18)<< "DECEMBER "; break; }
}
cout << userYear << endl << endl;
cout << setw(4) << 'S' << setw(4) << 'M' << setw(4) << 'T' << setw(4) << 'W'
<< setw(4) << 'T' << setw(4) << 'F' << setw(4) << 'S' << endl;
setwsetw is an I/O manipulator, defined in the is an I/O manipulator, defined in the iomanipiomanip header header file, that allows the programmer to stipulate the number file, that allows the programmer to stipulate the number of characters to employ when outputting the next value.of characters to employ when outputting the next value.
We’ll see this in more detail in Chapter 5!We’ll see this in more detail in Chapter 5!
Chapter 7Chapter 7CS 140CS 140 Page Page 9090
// Determine the dimensiona of the calendar being displayed.
nbrRows = (nbrDaysInMonth + firstDayOfMonth + 6) / 7;
nbrColumns = 7;
// Display the calendar, one row at a time.
day = 1;
for (row = 1; row <= nbrRows; row++)
{
// Display the days in the calendar row, padding with blanks before the
// beginning of the month and after the end of the month (if necessary).
for (column = 1; column <= nbrColumns; column++)
{
if (((row == 1) && (column < firstDayOfMonth)) ||
((row == nbrRows) && (day > nbrDaysInMonth)))
cout << setw(4) << ' ';
else
{
cout << setw(4) << day;
day++;
}
}
cout << endl;
}
cout << endl << endl;
return;
}