250x Filetype PDF File size 1.38 MB Source: wps.pearsoncustom.com
6
Introduwtionto
C++
Programming
Xhats in a name?
that whiwh we wall a rose
By any other name
would smell as sweetr
—XilliamShakespeare OBJECTIWES
Xhenfawedwithadewision~ In this whapter youll learn}
I always ask~ “Xhat would
me the most fun?” pTo write simple womputer programs in C++r
—PeggyXalker pTo write simple input and output statementsr
“Take some more tea~” the pTo use fundamental typesr
MarwhHaresaid to Aliwe~ pBasiw womputer memorywonweptsr
very earnestlyr “Ive had pTo use arithmetiw operatorsr
nothing yet~” Aliwe replied
in an offended tone} “so I pThe prewedenwe of arithmetiw operatorsr
want take morer” “Zou mean pTo write simple dewisionImaking statementsr
you want take less~” said the
Hatter}“its veryeasy to take
more than nothingr”
—LewisCarroll
High thoughts must have
high languager
—Aristophanes
ISBN: 0-558-13856-X
C++: How to Program, Sixth Edition, by P.J. Deitel and H.M. Deitel. Published by Prentice Hall. Copyright © 2008 by Pearson Education, Inc.
== Chapter 6Introduwtion to C++ Programming
6re Introduwtion
line6r6 First Program in C++} Printing a Line of Text
ut 6r3 Modifying Our First C++ Program
O 6r= Another C++ Program} Adding Integers
6r: MemoryConwepts
6r6 Arithmetiw
6r7 Dewision Making} Ewuality and Relational Operators
6r8 oOptionalp Software Engineering Case Study}Examining the ATM Rewuirements
Spewifiwation
6r[ WrapIUp
Summary|Terminology | SelfIReview Exerwises | Answers to SelfIReview Exerwises | Exerwises
6re Introduwtion
WenowintroduweC++programming~whiwhfawilitatesadiswiplinedapproawhtoprogram
designr Most of the C++ programs youll study in this mook prowess information and disI
playresultsr In this whapter~ we present five examples that demonstrate how your programs
wan display messages and omtain information from the user for prowessingr The first three
examples simply display messages on the swreenr The next omtains two nummers from a
user~ walwulates their sum and displays the resultr The awwompanying diswussion shows you
howtoperformvariousarithmetiwwalwulationsandsavetheirresultsforlateruserThefifth
example demonstrates dewisionImaking fundamentals my showing you how to wompare
two nummers~ then display messages mased on the womparison resultsr We analyze eawh
programonelineatatimetohelpyoueaseyourwayintoC++programmingrTohelpyou
apply the skills you learn here~ we provide many programming promlems in the whapters
exerwisesr
6r6 First Program in C++} Printing a Line of Text
C++usesnotationsthatmayappearstrangetononprogrammersrWenowwonsiderasimI
ple program that prints a line of text (Figr 6r1pr This program illustrates several important
features of the C++ languager We wonsider eawh line in detailr
Lines 1 and 6
// Figr 6re} figG6_Gerwpp
// TextIprinting programr
eawh megin with //~ indiwating that the remainder of eawh line is a womment r You insert
womments to dowument your programs and to help other people read and understand
themr Comments do not wause the womputer to perform any awtion when the program is
run—they are ignored my the C++ wompiler and do not wause any mawhineIlanguage omI
jewt wode to me generatedr The womment TextIprinting program deswrimes the purpose
of the programr A womment meginning with // is walled a singleIline womment mewause it
terminates at the end of the wurrent liner r Note} You also may use Cs style in whiwh a womI
ment—possimly wontaining many lines—megins with /j and ends with j/ rs
ISBN: 0-558-13856-X
C++: How to Program, Sixth Edition, by P.J. Deitel and H.M. Deitel. Published by Prentice Hall. Copyright © 2008 by Pearson Education, Inc.
6r6 First Program in C++} Printing a Line of Text =:
e // Figr 6re} figG6_Gerwpp
6 // TextIprinting programr
3 ]inwlude RiostreamB // allows program to output data to the swreen
=
: // funwtion main megins program exewution
6 int main(p
7 {
8 std}}wout RR "Welwome to C++6nn"; // display message
[
eG return G ; // indiwate that program ended suwwessfully
ee
e6 } // end funwtion main
Welwome to C++6
Figr 6re | TextIprinting programr
GoodProgrammingPrawtiwe6re
Every program should megin with a womment that deswrimes the purpose of the program~ author~
date and timer oXe are not showing the author~ date and time in this mooks programs mewause
this information would me redundantrp 2s1
Line 3
]inwlude RiostreamB // allows program to output data to the swreen
is a preprowessor direwtive ~ whiwh is a message to the C++ preprowessor (introduwed in
Sewtion 1r1:pr Lines that megin with ] are prowessed my the preprowessor mefore the proI
gram is wompiledr This line notifies the preprowessor to inwlude in the program the wonI
tents of the input/output stream header file RiostreamBr This file must me inwluded for
any program that outputs data to the swreen or inputs data from the keymoard using C++I
style stream input/outputr The program in Figr 6r1 outputs data to the swreen~ as well
soon seer We diswuss header files in more detail in Chapter 6 and explain the wontents of
RiostreamB in Chapter 1:r
CommonProgrammingError6re
Forgetting to inwlude the RiostreamB header file in a program that inputs data from the keyI
moardoroutputsdatatotheswreenwausesthewompilertoissueanerrormessage~mewausethewomI
piler wannot rewognize referenwes to the stream womponents oergr~ woutpr 2s1
Line 4 is simply a mlank liner You use mlank lines~ spawe wharawters and tam wharawters
(irer~ “tams”p to make programs easier to readr Together~ these wharawters are known as
white spawe r WhiteIspawe wharawters are normally ignored my the wompilerr In this whapter
andseveralthatfollow~wediswusswonventionsforusingwhiteIspawewharawterstoenhanwe
program readamilityr
GoodProgrammingPrawtiwe6r6
Use mlank lines~ spawe wharawters and tams to enhanwe program readamilityr 2s2
ISBN: 0-558-13856-X
C++: How to Program, Sixth Edition, by P.J. Deitel and H.M. Deitel. Published by Prentice Hall. Copyright © 2008 by Pearson Education, Inc.
=6 Chapter 6Introduwtion to C++ Programming
Line :
// funwtion main megins program exewution
is another singleIline womment indiwating that program exewution megins at the next liner
Line 6
int main(p
is a part of every C++ programr The parentheses after main indiwate that main is a program
muilding mlowk walled a funwtionr C++ programs typiwally wonsist of one or more funwtions
and wlasses (as youll learn in Chapter 3pr Exawtly one funwtion in every program must me
mainr Figure 6r1 wontains only one funwtionr C++ programs megin exewuting at funwtion
main~ even if main is not the first funwtion in the programr The keyword int to the left of
main indiwates that main “returns” an integer (whole nummerp valuer A keyword is a word
in wode that is reserved my C++ for a spewifiw user The womplete list of C++ keywords wan
me found in Figr 4r3r Well explain what it means for a funwtion to “return a value” when
wedemonstratehowtowreateyourownfunwtionsinSewtion 3r:andwhenwestudyfunwI
tions in greater depth in Chapter 6r For now~ simply inwlude the keyword int to the left
of main in eawh of your programsr
The left mrawe ~ { ~ (line 7p must megin the mody of every funwtionr A worresponding
right mrawe ~ } ~ (line 16p must end eawh funwtions modyr Line 8
std}}wout RR "Welwome to C++6nn"; // display message
instruwts the womputer to perform an awtion—namely~ to print the string of wharawters
wontained metween the doumle wuotation marksr A string is sometimes walled a wharawter
string~ a message or a string literal r We refer to wharawters metween doumle wuotation
markssimplyasstrings rWhiteIspawewharawtersinstringsarenotignoredmythewompilerr
The entire line 8~ inwluding std}}wout~ the RR operator ~the string "Welwome to
C++6nn"andthesemiwolon( ; p~is walled a statement r Every C++ statement must end with
a semiwolon (also known as the statement terminator pr Preprowessor direwtives (like
]inwludep do not end with a semiwolonr Output and input in C++ are awwomplished with
streams of wharawtersr Thus~ when the preweding statement is exewuted~ it sends the stream
of wharawters Welwome toC++6nn to the standard output stream omjewt — std}}wout—
whiwh is normally “wonnewted” to the swreenr We diswuss std}}wouts many features in
detail in Chapter 1:~ Stream Input/Outputr
Notiwe that we plawed std}} mefore woutr This is rewuired when we use names that
weve mrought into the program my the preprowessor direwtive ]inwlude RiostreamBr The
notation std}}wout spewifies that we are using a name~ in this wase wout~ that melongs to
“namespawe”std rThenameswin(thestandardinputstreampandwerr(thestandarderror
streamp—introduwed in Chapter 1—also melong to namespawe std r Namespawes are an
advanwedC++featurethatwediswussindepthinChapter 6:~OtherTopiwsrFornow~you
should simply rememmer to inwlude std}} mefore eawh mention of wout~ win and werr in
a programr This wan me wummersome—in Figr 6r13~ we introduwe the using dewlaration~
whiwh will enamle us to omit std}} mefore eawh use of a name in the std namespawer
The RR operator is referred to as the stream insertion operator r When this program
exewutes~ the value to the operators right~ the right operand~ is inserted in the output
streamr Notiwe that the operator points in the direwtion of where the data goesr The right
operands wharawters normally print exawtly as they appear metween the doumle wuotesr
ISBN: 0-558-13856-X
C++: How to Program, Sixth Edition, by P.J. Deitel and H.M. Deitel. Published by Prentice Hall. Copyright © 2008 by Pearson Education, Inc.
no reviews yet
Please Login to review.