Chapter 2 - Simple C++ Programs

  • Upload
    baotvdn

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    1/57

    Copyright © 2012 Pearson Education, Inc.

    Chapter 2

    Simple C++ Programs

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    2/57

    Copyright © 2012 Pearson Education, Inc.

    Outline

    O!ecti"es1. C++ Program Structure

    2. Constant and #ariales

    $. C++ Classes

    %. C++ Operators

    &. Standard Input and Output

    '. (uilding C++ Solutions )ith I*Es

    . (asic unctions in C++ Standard -irary

    . Prolem Sol"ing /pplied

    . System -imitations

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    3/57

    Copyright © 2012 Pearson Education, Inc.

    O!ecti"es

    *e"elop prolemsol"ing solutions in

    C++ containing

    3Simple arithmetic computations

    3 In4ormation printed on the screen

    3 5sersupplied In4ormation 4rom 6eyoard

    3 Programmerde4ined data types

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    4/57

    C++

    ProgramStructure

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    5/57

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    6/57

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    7/57

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    8/57

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    9/57

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    10/57

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    11/57

    /*--------------------------------------------------------

     * Program chapter1_1

    * This program computes the distance between two points.

    */

    #include // Reuired !or cout" endl.

    #include  // Reuired !or srt$

    using namespace std%

    int main$ &

    // 'eclare and initiali(e ob)ects.

      double 11$" +1,$" $" +$"

      side1" side" distance%

    // 0ompute sides o! a right triangle.

      side1 - 1%

      side + - +1%

      distance srtside1*side1 2 side*side$%

    // Print distance.

      cout

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    12/57

    Constants

    and

    #ariales

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    13/57

    Constants and #ariales

    3 Constants and "ariales represent memory locations that

    )e re4erence in our program solutions.

    3 Constants are o!ects that store speci4ic data that can not e

    modi4ied.

    – 10 is an integer constant

    – 4.5 is a 4loating point constant

    – "The distance between the two points is" is a string

    constant

      FaF is a character constant

    3 #ariales are named memory locations that store "alues that can be

    modified.

    – double x1(1.0), x2(4.5), side1;

    – side1 = x2 x1;

    – x1, x2 and side1 are eGamples o4 "ariales that can e modi4ied.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    14/57

    Initial #alues

    3 C++ does not pro"ide initial "alues

    4or "ariales.

      @hus using the "alue o4 a "ariale e4ore it is

    initialiBed may result in =garage7.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    15/57

    Aemory Snapshots

    3 Aemory =snapshots7 are diagrams that

    sho) the types and contents o4 "ariales

    at a particular point in time.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    16/57

    #alid C++ Identi4iers

    3 Aust egin )ith an alphaetic

    character or the underscore character =H7

    3  /lphaetic characters may e either upper or

    lo)er case.  C++ is C/SE SESI@I#E, so =a7 JK =/7, etcL

    3 Aay contain digits, ut not in as the 4irst character.

    3 Aay e o4 any length, ut the 4irst $1 characters

    must e uniMue.

    3 Aay O@ e C++ 6ey)ords.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    17/57

    C++ Ney)ords

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    18/57

    C++ Identi4iers

    3 Should e care4ully chosen to re4lect

    the contents o4 the o!ect.

      @he name should also re4lect the units o4

    measurements )hen applicale.

    3 Aust e declared >and there4ore typed?

    e4ore they may e used.

      C++ is a strongly typed programming

    language.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    19/57

    Common C++ *ata @ypes

    3 Ney)ord EGample o4 a constant

    – bool t!ue

    – cha! 5

    – int 25

    – double 25.0

    – st!in# "hello"

    99$include%st!in#&

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    20/57

    *eclarations

    3  / type declaration statement de4inesne) identi4iers and allocates memory.

    3  /n initial "alue may e assigned to a memory

    location at the time an identi4ier is de4ined. 

    Copyright © 2012 Pearson Education, Inc.

    Syntax[modifier] type specifier identifier [= initial value];[modifier] type specifier identifier[(initial value)];

    EGamples

    double 1" +15$%int counter5%const int 789_:8;45%bool error!alse$%char comma"$%

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    21/57

    Symolic Constants

    3  / symolic constant is de4ined in a declaration

    statement using the modi4ier const.

    3  / symolic constant allocates memory 4or an

    o!ect that can not e modi4ied duringeGecution o4 the program. Any attempt to

    modify a constant will be flagged as a syntax

    error by the compiler .

    3  / symolic constant must e initialiBed in the

    declaration statement.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    22/57

    C++ Classes

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    23/57

    Class *eclarations

    3 Speci4y a programmerde4ined type9o!ect.

    3 (egin )ith 6ey)ord =class7 4ollo)ed y the

    name >i.e. identi4ier? o4 the type.

      Class de4inition is made in a code loc6.

      Class memers may include data >attriutes?

    and methods >4unctions?.

      #isiilities o4 public , protected , and private are used to control access to class memers

      / semicolon must 4ollo) the closing rac6et D

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    24/57

    Class Aethods

    3 *e4ine the operations that can eper4ormed on class o!ects.

      / constructor  is a special method that is eGecuted

    )hen o!ects o4 the class type are created

    >instantiated ?.  Constructors must ha"e the same name as the class.

      / class may de4ine multiple constructors to allo)

    greater 4leGiility in creating o!ects.

    3 @he de4ault constructor is the one that has no parameters.3 ParameteriBed constructors pro"ide initial "alues o4 data

    memers.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    25/57

    Class *e4initions

    3 O4ten declared in t)o parts

      @he class declaration is typically )ritten in a 4ile

    named =classame.h7

    3 *e4ines the class including data memers and theheaders o4 the class methods.

      @he implementation o4 class methods is

    typically )ritten in a 4ile named

    =classame.cpp7

    3

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    26/57

    Class SyntaG

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    27/57

    5sing a Class

    3 Once a class is de4ined, you may use

    the class as a type speci4ier.

      Rou must include the class de4inition >i.e. header 4ile?

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    28/57

    C++ Operators

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    29/57

     /ssignment Operator 

    3 @he assignment operator >K? is used

    in C++ to assign a "alue to a memory

    location.

    3 @he assignment statementx1 = 1.0;

      assigns the "alue 1.0 to the "ariale x1.

      @hus, the "alue 1.0 is stored in the memorylocation associated )ith the identi4ier x1.

    >ote x1 must ha"e een pre"iously declared.?

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    30/57

    Order o4 @ypes

    3 (ecause di44erent types are

    di44erent

    representations, 4reMuently )e

    need to con"ert et)een types.  Sometimes these con"ersions may

    loose in4ormation.

      Con"ersion 4rom lo)er types to higher

    types results in no loss o4 in4ormation.  Con"ersion 4rom higher types to lo)er

    types may loose in4ormation.

    Copyright © 2012 Pearson Education, Inc.

    igh!

    "ow!

    long doubledoublefloat

    long integer integer short integer 

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    31/57

     /ssignment Statements

     Assignment operators must not be

    confused with equality.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    32/57

     /rithmetic EGpressions

    3 EGpressions appearing in assignment

    statements 4or numeric "ariales may e

    simple literals >e.g. x1 = 10.4;?, reading

    the "alue stored in a "ariale >e.g. x2=x1;?, or e more compleG eGpressions

    in"ol"ing the e"aluation o4 one or more

    operators >e.g. x1 = '.4x2 10.4?.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    33/57

     /rithmetic Operators

    3  /ddition #

    3 Sutraction $

    3 Aultiplication %

    3 *i"ision  &3 Aodulus '

      Aodulus returns remainder o4 di"ision et)een t)o

    integers

      EGample' returns a "alue o4 1

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    34/57

    Operator (asics

    3 @he 4i"e operators >: 9 + ? are

    binary operators operators that reMuire

    t)o arguments >i.e. operands?.

    3 C++ also include operators that reMuire

    only a single argument unary

    operators.

      or eGample, a plus or a minus sign

    preceding an eGpression can e unary

    operators >e.g. x2?.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    35/57

    Integer *i"ision

    3 *i"ision et)een t)o integers results

    in an integer.

    3 @he result is truncated, not rounded

    3 EGample

    @he eGpression &* e"aluates to 1

    @he eGpression *&+ e"aluates to 0

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    36/57

    AiGed Operations

    3 (inary operations on t)o "alues o4 

    same type yield a "alue o4 that type >e.g.

    di"iding t)o integers results in an integer?.

    3 (inary operations et)een "alues o4

    di44erent types is a mixed operation.

      #alue o4 the lo)er type must e con"erted to

    the higher type e4ore per4orming operation.

      Tesult is o4 the higher type.

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    37/57

    Casting

    3 @he cast operator.

      @he cast operator is a unary operator that reMuests

    that the value o4 the operand e cast, or changed, to

    a ne) type 4or the neGt computation. ,he type of the

    operand is not affected-

    3 EGampleint count>10?, sum>&&?

    doule a"eragea"erage K >doule?sum9count

    Copyright © 2012 Pearson Education, Inc.

    Memory snapshot:

    int count

    int sum

    double average 

    10

    &&

    &.&

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    38/57

    O"er4lo) and 5nder4lo)

    3 O"er4lo)  ans)er too large to storeEGample using 1' its 4or integers!esult = '2000 5'2;

    3 EGponent o"er4lo)  ans)er7s eGponent is too largeEGample using 4loat, )ith eGponent range $ to $!esult = '.25e2* 1.0e15;

    3 EGponent under4lo)  ans)er7s eGponent too smallEGample using 4loat, )ith eGponent range $ to $!esult = '.25e2* 1.0e15;

    Copyright © 2012 Pearson Education, Inc.

    I t d * t

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    39/57

    Increment and *ecrement

    Operators3 Increment Operator ##

    3 post increment x##;

    3 pre increment ##x;

    3 *ecrement Operator $ $3 post decrement x$ $;

    3 pre decrement $ $x;

    3 or eGamples assume 6K& prior to eGecuting the

    statement.3 mK ++6 99 oth m and 6 ecome '

    3 n K 6 99 n ecomes & and 6 ecomes %

    Copyright © 2012 Pearson Education, Inc.

    / i t d / i t

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    40/57

     /re"iated /ssignment

    Operators

    operator example e.uivalent statement 

    =   x+=2;  x=x2;

    =   x-=2; x=x2;

    =   x*=y; x=x+;

    =   x/=y; x=x+;-=   x%=y; x=x-+;

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    41/57

    Operator Precedence

    Copyright © 2012 Pearson Education, Inc.

    /recedence 0perator Associativity

    1 Parenthesis >? Innermost irst

    2 5nary operators+ ++ >type? Tight to le4t

    $ (inary operators: 9

    -e4t to right

    % (inary operators+

    -e4t to right

    & /ssignment OperatorsK +K K :K 9K K

    Tight to le4t

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    42/57

    Standard Input 9 Output

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    43/57

    Sample Output cout

    cout is an ost!ea/ o!ect, de4ined in the header4ile iost!ea/

    cout is de4ined to stream data to standard output

    >the display? e use the output operator UU )ith cout to

    output the "alue o4 an eGpression.

    ;eneral ormcout 11 eGpression 11 eGpression;

    2ote! An expression is a 3## constant4 identifier4 formula4 or functioncall-

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    44/57

    Simple Input cin

    cin is an ist!ea/ o!ect de4ined

    in the header 4ile iost!ea/

    cin is de4ined to stream data 4rom standard input

    >the 6eyoard?

    3 Ve use the input operator && )ith cin to assign

    "alues to "ariales

      ;eneral ormcin && identifier  && identifier ;

    3 2ote! 5ata entered from the 6eyboard must be compatible with the data

    type of the variable-

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    45/57

    Characters and Input

    3 @he input operator WW s6ips all)hitespace characters.

    3 @he get>? method gets the neGt character.

    3 EGampleint G

    char ch

    cin WW G WW chcin WW G

    cin.get>ch?

    Copyright © 2012 Pearson Education, Inc.

    Input stream:

    45 c

    39

     b

    Memory Snapshot

    x ch

    x ch

    45 ‘c’

    39 ‘\n ’

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    46/57

    Aanipulators and Aethods

    3 endl places a ne)line character in the outputu44er and flushes the buffer.

    3 set4>? and unset4>?

    Copyright © 2012 Pearson Education, Inc.

    lag Aeaning

    iossho)point display the decimal pointios4iGed 4iGed decimal notation

    iosscienti4ic scienti4ic notation

    Ios::setprecision>n? set the numer o4 signi4icant digits to e printed to theinteger "alue n

    Ios::set)>n? set the minimum numer o4 columns 4or printing theneGt "alue to the integer "alue n

    iosright right !usti4ication

    iosle4t le4t !usti4ication

    ( ildi C++ S l ti

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    47/57

    (uilding C++ Solutions

    )ith I*Es

    Copyright © 2012 Pearson Education, Inc.

    I t t d * l t

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    48/57

    Integrated *e"elopment

    En"ironments >I*Es?3 I*Es are so4t)are pac6ages designed

    to 4acility the de"elopment o4 so4t)are

    solutions.

    3 I*Es include  Code editors

      Compiler 

      *eugger   @esting tools

      Aany additional help4ul toolsL

    Copyright © 2012 Pearson Education, Inc.

    ( i ti i C++

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    49/57

    (asic unctions in C++

    Standard -irary

    Copyright © 2012 Pearson Education, Inc.

    (asic C++ Aath

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    50/57

    (asic C++ Aath

    unctions

    Copyright © 2012 Pearson Education, Inc.

    abs!"# computes absolute value o "

    s$rt!"# computes s$uare root o "% &here" '()

     po&!"%y# computes "y

    ceil!"# nearest integer larger than "

    loor!"# nearest integer smaller than "

    e"p!"# computes e"

    log!"# computes ln "% &here " ')

    log*)!"# computes log*)"% &here "')

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    51/57

    @rigonometric unctions

    Copyright © 2012 Pearson Education, Inc.

    sin!"# sine o "% &here " is in radians

    cos!"# cosine o "% &here " is in radians

    tan!"# tangent o "% &here " is in radians

    asin!"# +his unction computes the arcsine% or inverse sine% o "% &here "must be in the range ,-*% *./

    +he unction returns an angle in radians in the range ,-012% 012./

    acos!"# +his unction computes the arccosine% or inverse cosine% o "%&here " must be in the range ,-*% *./

    +he unction returns an angle in radians in the range ,)% 0./

    atan!"# +his unction computes the arctangent% or inverse tangent% o "/

    +he unction returns an angle in radians in the range ,-012% 012./

    atan2!y%"# +his unction computes the arctangent or inverse tangent o thevalue y1"/

    +he unction returns an angle in radians in the range ,-0% 0./

    Common unctions

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    52/57

    Common unctions

    *e4ined in UcctypeW

    Copyright © 2012 Pearson Education, Inc.

    isalpha!ch# eturns true i ch is an upper or lo&er case letter/

    isdigit!ch# eturns true i ch is a decimal digit

    isspace!ch# eturns true i ch is a &hitespace character/

    islo&er!ch# eturns true i ch is an lo&er case letter/

    isupper!ch# eturns true i ch is an upper case letter/

    tolo&er!ch# eturns the lo&ercase version o ch i ch is an uppercasecharacter% returns ch other&ise/

    toupper!ch# eturns the uppercase version o ch i ch is a lo&ercasecharacter% returns ch other&ise/

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    53/57

    Copyright © 2012 Pearson Education, Inc.

    Prolem Sol"ing /pplied

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    54/57

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    55/57

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    56/57

    System -imitations

    Copyright © 2012 Pearson Education, Inc.

  • 8/17/2019 Chapter 2 - Simple C++ Programs

    57/57