CS10 Coursewares

Embed Size (px)

Citation preview

  • 8/3/2019 CS10 Coursewares

    1/290

    C++C++ forfor

    Engineers and ScientistsEngineers and Scientists

    Second EditionSecond Edition

    Chapter 1

    Introduction

  • 8/3/2019 CS10 Coursewares

    2/290

    C++ for Engineers and Scientists, Second Edition 2

    ObjectivesObjectives

    Introduction to Programming

    Problem Solution and Software Development

    Algorithms Common Programming Errors

    Computer Hardware and Storage Concepts

  • 8/3/2019 CS10 Coursewares

    3/290

    C++ for Engineers and Scientists, Second Edition 3

    Introduction to ProgrammingIntroduction to Programming

    Program: self-contained set of instructions

    used to operate a computer to produce a

    specific result Also called software

    Programming: the process of writing a

    program, or software

  • 8/3/2019 CS10 Coursewares

    4/290

    C++ for Engineers and Scientists, Second Edition 4

    Introduction to Programming:Introduction to Programming:

    Machine LanguageMachine Language Machine language programs, also called

    executables, consist of binary instructions

    Each instruction has two parts:

    Instruction part: the operation to be performed;also called an opcode

    Address part: memory address of the data to beused

    Each class of computer has its own particularmachine language

    Writing in machine language is tedious!

  • 8/3/2019 CS10 Coursewares

    5/290

    C++ for Engineers and Scientists, Second Edition 5

    Introduction to Programming:Introduction to Programming:

    Assembly LanguagesAssembly Languages

    Assembly Language: programming language

    with symbolic names for opcodes, and decimals

    or labels for memory addressesExample:

    ADD 1, 2

    MUL 2, 3

    Assembly language programs must be

    translated into machine instructions, using an

    assembler

  • 8/3/2019 CS10 Coursewares

    6/290

  • 8/3/2019 CS10 Coursewares

    7/290

    C++ for Engineers and Scientists, Second Edition 7

    Introduction to Programming:Introduction to Programming:

    LowLow-- and Highand High--Level LanguagesLevel Languages

    Low-level languages: languages that use

    instructions tied directly to one type of computer

    Examples: machine language, assemblylanguage

    High-level languages: instructions resemble

    written languages, such as English,and can be

    run on a variety of computer types

    Examples: Visual Basic, C, C++, Java

  • 8/3/2019 CS10 Coursewares

    8/290

    C++ for Engineers and Scientists, Second Edition 8

    Introduction to Programming: LowIntroduction to Programming: Low--

    and Highand High--Level Languages (continued)Level Languages (continued)

    Source code: the programs written in a high-or low-level language

    Source code must be translated to machineinstructions in one of two ways:

    Interpreter: each statement is translatedindividually and executed immediately after

    translation Compiler: all statements are translated andstored as an executable program, orobjectprogram; execution occurs later

  • 8/3/2019 CS10 Coursewares

    9/290

    C++ for Engineers and Scientists, Second Edition 9

    Introduction to Programming: LowIntroduction to Programming: Low--

    and Highand High--Level Languages (continued)Level Languages (continued)

    Large C++ programs may be stored in two or

    more separate program files due to

    Use of previously written code

    Use of code provided by the compiler

    Modular design of the program (for reusability of

    components)

    Linker: combines all of the compiled code

    required for the program

  • 8/3/2019 CS10 Coursewares

    10/290

    C++ for Engineers and Scientists, Second Edition 10

    Introduction to Programming:Introduction to Programming:

    Procedural and Object OrientationsProcedural and Object Orientations

    Programs can also be classified by their

    orientation:

    Procedural: available instructions are used tocreate self-contained units called procedures

    Object-oriented: reusable objects, containing

    code and data, are manipulated

    Object-oriented languages support reusing

    existing code more easily

  • 8/3/2019 CS10 Coursewares

    11/290

    C++ for Engineers and Scientists, Second Edition 11

    Introduction to Programming: ProceduralIntroduction to Programming: Procedural

    and Object Orientations (continued)and Object Orientations (continued)

    Figure 1.2

    Creating anexecutable C++

    program.

  • 8/3/2019 CS10 Coursewares

    12/290

    C++ for Engineers and Scientists, Second Edition 12

    Introduction to Programming:Introduction to Programming:

    Application and System SoftwareApplication and System Software

    Application software: programs written toperform particular tasks for users

    System software: collection of programs tooperate the computer system

    System software must be loaded first; calledbooting the system

    Bootstrap loader: a permanent, automaticallyexecuted component to start the boot process

  • 8/3/2019 CS10 Coursewares

    13/290

    C++ for Engineers and Scientists, Second Edition 13

    Introduction to Programming:Introduction to Programming:

    Application and System SoftwareApplication and System Software

    (continued)(continued)

    Operating system: the set of system programs

    used to operate and control a computer; also

    called OS Tasks performed by the OS include

    Memory management

    Allocation of CPU time

    Control of input and output

    Management of secondary storage devices

  • 8/3/2019 CS10 Coursewares

    14/290

    C++ for Engineers and Scientists, Second Edition 14

    Introduction to Programming:Introduction to Programming:

    Application and System SoftwareApplication and System Software

    (continued)(continued)

    Multi-usersystem: a system that allows more

    than one user to run programs on the computer

    simultaneously Multitasking system: a system that allows

    each user to run multiple programs

    simultaneously; also called multiprogrammed

    system

  • 8/3/2019 CS10 Coursewares

    15/290

    C++ for Engineers and Scientists, Second Edition 15

    Introduction to Programming:Introduction to Programming:

    The Development of C++The Development of C++

    The purpose of most application programs isto process data to produce specific results

    Figure 1.3 Basic procedural operations.

  • 8/3/2019 CS10 Coursewares

    16/290

    C++ for Engineers and Scientists, Second Edition 16

    Introduction to Programming:Introduction to Programming:

    The Development of C++ (continued)The Development of C++ (continued) Early procedural languages included

    FORTRAN: Formula Translation

    ALGOL: Algorithmic Language

    COBOL: Common Business Oriented Language

    BASIC: Beginners All-purpose Symbolic

    Instruction Code

    Pascal C

  • 8/3/2019 CS10 Coursewares

    17/290

    C++ for Engineers and Scientists, Second Edition 17

    Introduction to Programming:Introduction to Programming:

    The Development of C++ (continued)The Development of C++ (continued)

    Early object-oriented language:

    C++

  • 8/3/2019 CS10 Coursewares

    18/290

    C++ for Engineers and Scientists, Second Edition 18

    Problem Solution andProblem Solution and

    Software DevelopmentSoftware Development Software development procedure: method

    for solving problems and creating software

    solutions

    Consists of three phases:

    Phase I: Development and Design

    Phase II: Documentation

    Phase III: Maintenance

    Software engineering: discipline concerned

    with creating efficient, reliable, maintainable

    software

  • 8/3/2019 CS10 Coursewares

    19/290

    C++ for Engineers and Scientists, Second Edition 19

    Problem Solution and SoftwareProblem Solution and Software

    Development (continued)Development (continued)

    Figure 1.6 The three phases of software development.

  • 8/3/2019 CS10 Coursewares

    20/290

    C++ for Engineers and Scientists, Second Edition 20

    Problem Solution andProblem Solution and

    Software Development:Software Development:

    Phase I. Development and DesignPhase I. Development and Design Program requirement: request for a program

    or a statement of a problem

    After a program requirement is received, PhaseI begins

    Phase I consists of four steps:

    Analysis

    Design

    Coding

    Testing

  • 8/3/2019 CS10 Coursewares

    21/290

    C++ for Engineers and Scientists, Second Edition 21

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Figure 1.7 The development and design steps.

  • 8/3/2019 CS10 Coursewares

    22/290

  • 8/3/2019 CS10 Coursewares

    23/290

    C++ for Engineers and Scientists, Second Edition 23

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Step 2: Develop a Solution

    Algorithm: the exact steps used to solve a

    problem Algorithm is usually defined at high level, then

    refined to detailed lower levels

    Structure level diagrams may be used torepresent the levels of analysis

  • 8/3/2019 CS10 Coursewares

    24/290

    C++ for Engineers and Scientists, Second Edition 24

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Figure 1.8 First-level structure diagram.

  • 8/3/2019 CS10 Coursewares

    25/290

    C++ for Engineers and Scientists, Second Edition 25

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Figure 1.9 Second-level refinement structure diagram.

  • 8/3/2019 CS10 Coursewares

    26/290

    C++ for Engineers and Scientists, Second Edition 26

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Step 3: Code the Solution

    Also called writing the program, and

    implementing the solution Program should contain well-defined patterns or

    structures of the following types:

    Sequence

    Selection

    Iteration

    Invocation

  • 8/3/2019 CS10 Coursewares

    27/290

    C++ for Engineers and Scientists, Second Edition 27

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued) Sequence: defines the order in which

    instructions are executed

    Selection: allows a choice between differentoperations, based on some condition

    Iteration: allows the same operation to be

    repeated based on some condition; also called

    loopingorrepetition Invocation: involves invoking a set of

    statements when needed

  • 8/3/2019 CS10 Coursewares

    28/290

    C++ for Engineers and Scientists, Second Edition 28

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Step 4: Test and Correct the Program

    Testing: method to verify correctness and that

    requirements are met Bug: a program error

    Debugging: the process of locating an error,

    and correcting and verifying the correction

    Testing may reveal errors, but does not

    guarantee the absence of errors

  • 8/3/2019 CS10 Coursewares

    29/290

    C++ for Engineers and Scientists, Second Edition 29

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Testing requires the use of meaningful,

    representative test data

    Impossible to test all possible combinations ofdata and operations in a complex program

    Testing plans must be developed to ensure

    good coverage in testing

    Testing usually requires more time than other

    steps in Phase I

  • 8/3/2019 CS10 Coursewares

    30/290

    C++ for Engineers and Scientists, Second Edition 30

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase I (continued)Development: Phase I (continued)

    Relative effort for steps in Phase I

  • 8/3/2019 CS10 Coursewares

    31/290

  • 8/3/2019 CS10 Coursewares

    32/290

    C++ for Engineers and Scientists, Second Edition 32

    Problem Solution and SoftwareProblem Solution and Software

    Development: Phase III. MaintenanceDevelopment: Phase III. Maintenance Maintenance includes

    Ongoing correction of newly discovered bugs

    Revisions to meet changing user needs Addition of new features

    Maintenance usually the longest phase, andmay be the primary source of revenue

    Good documentation vital for effectivemaintenance

  • 8/3/2019 CS10 Coursewares

    33/290

    C++ for Engineers and Scientists, Second Edition 33

    Problem Solution and SoftwareProblem Solution and Software

    Development: BackupDevelopment: Backup

    Backup: process of making copies of program

    code and documentation on a regular basis

    Backup copies = insurance against loss ordamage

    Consider using off-site storage for additional

    protection

  • 8/3/2019 CS10 Coursewares

    34/290

    C++ for Engineers and Scientists, Second Edition 34

    AlgorithmsAlgorithms

    Algorithm: the step-by-step sequence of

    instructions that describe how the data is to be

    processed to produce the desired output

    Programming = the translation of the selected

    algorithm into a language the computer can use

  • 8/3/2019 CS10 Coursewares

    35/290

    C++ for Engineers and Scientists, Second Edition 35

    Algorithms (continued)Algorithms (continued)

    Example: Calculate the sum of all whole numbers from1 through 100

  • 8/3/2019 CS10 Coursewares

    36/290

    C++ for Engineers and Scientists, Second Edition 36

    Algorithms (continued)Algorithms (continued)

  • 8/3/2019 CS10 Coursewares

    37/290

    C++ for Engineers and Scientists, Second Edition 37

    Algorithms (continued)Algorithms (continued)

  • 8/3/2019 CS10 Coursewares

    38/290

    C++ for Engineers and Scientists, Second Edition 38

    Algorithms (continued)Algorithms (continued)

    Pseudocode: English-like phrases used to

    describe the algorithm

    Formula: description of a mathematical

    equation

    Flowchart: diagram showing the flow of

    instructions in an algorithm

    Flowcharts use special symbols

  • 8/3/2019 CS10 Coursewares

    39/290

    C++ for Engineers and Scientists, Second Edition 39

    Algorithms: FlowchartsAlgorithms: Flowcharts

  • 8/3/2019 CS10 Coursewares

    40/290

    C++ for Engineers and Scientists, Second Edition 40

    Algorithms: Flowcharts (continued)Algorithms: Flowcharts (continued)

  • 8/3/2019 CS10 Coursewares

    41/290

    C++ for Engineers and Scientists, Second Edition 41

    Algorithms: Flowcharts (continued)Algorithms: Flowcharts (continued)

    Figure 1.12 Flowchart forcalculating the average of three

    numbers.

  • 8/3/2019 CS10 Coursewares

    42/290

    C++ for Engineers and Scientists, Second Edition 42

    Common Programming ErrorsCommon Programming Errors

    Common errors include

    Starting to write the program before fully

    understanding the requirements and the

    algorithm to be used

    Failing to make backups periodically

    Failing to provide complete, precise instructions

    in the programming language

  • 8/3/2019 CS10 Coursewares

    43/290

    C++ for Engineers and Scientists, Second Edition 43

    SummarySummary

    Software: programs used to operate a

    computer

    Programming language types:

    Low-level languages

    Machine language (executable) programs

    Assembly languages

    High-level languages Compiler and interpreter languages

  • 8/3/2019 CS10 Coursewares

    44/290

    C++ for Engineers and Scientists, Second Edition 44

    Summary (continued)Summary (continued)

    Software engineering: discipline concerned with

    creating readable, efficient, reliable, and

    maintainable programs

    Three phases in software development:

    Program development and design

    Documentation

    Maintenance

  • 8/3/2019 CS10 Coursewares

    45/290

    C++ for Engineers and Scientists, Second Edition 45

    Summary (continued)Summary (continued)

    Four steps in program development and design: Analyze the problem

    Develop a solution

    Code the solution Test and correct the solution

    Algorithm: step-by-step procedure that

    describes how a task is performed

    Computer program: self-contained unit ofinstructions and data used to operate a

    computer to produce a desired result

  • 8/3/2019 CS10 Coursewares

    46/290

    C++ for Engineers and Scientists, Second Edition 46

    Summary (continued)Summary (continued)

    Four fundamental control structures used in

    coding:

    Sequence Selection

    Iteration

    Invocation

  • 8/3/2019 CS10 Coursewares

    47/290

    C++ for Engineers and Scientists, Second Edition 47

    Appendix: Computer Hardware andAppendix: Computer Hardware and

    Storage ConceptsStorage Concepts

    Computer hardware: components that support

    the capabilities of the computer

  • 8/3/2019 CS10 Coursewares

    48/290

    C++ for Engineers and Scientists, Second Edition 48

    Appendix: Computer Hardware andAppendix: Computer Hardware and

    Storage Concepts (continued)Storage Concepts (continued)

    Components include:

    Arithmetic and logic unit (ALU): performs

    arithmetic and logic functions

    Control unit: directs and monitors overall

    operations

    Memory unit: stores instructions and data

    Input and output (I/O) unit: interfaces toperipheral devices

    Secondary storage: nonvolatile permanent

    storage such as hard disks

  • 8/3/2019 CS10 Coursewares

    49/290

    C++ for Engineers and Scientists, Second Edition 49

    Appendix: Computer Hardware andAppendix: Computer Hardware and

    Storage Concepts (continued)Storage Concepts (continued)

    Central processing unit (CPU), also called

    microprocessor, combines the ALU and

    control unit on a single chip

    Figure 1.15 VLSI chip connections for a desktop computer.

  • 8/3/2019 CS10 Coursewares

    50/290

    C++ for Engineers and Scientists, Second Edition 50

    Appendix: Computer Hardware andAppendix: Computer Hardware and

    Storage Concepts (continued)Storage Concepts (continued)

    Computer storage:

    Bit: smallest unit of data; value of 0 or 1

    Byte: grouping of 8 bits representing a singlecharacter

    Character codes: collection of patterns of 0s

    and 1s representing characters; examples

    include

    ASCII

    EBCDIC

  • 8/3/2019 CS10 Coursewares

    51/290

    C++ for Engineers and Scientists, Second Edition 51

    Appendix: Computer Hardware andAppendix: Computer Hardware and

    Storage Concepts (continued)Storage Concepts (continued)

    Number codes: patterns used to storenumbers

    Twos Complement number code: represents

    a decimal number as a binary number of 0s and1s

  • 8/3/2019 CS10 Coursewares

    52/290

    C++ for Engineers and Scientists, Second Edition 52

    Appendix: Computer Hardware andAppendix: Computer Hardware and

    Storage Concepts (continued)Storage Concepts (continued)

    Word: grouping of one or more bytes

    Number of bytes in a word determines themaximum and minimum values that can be

    stored:

  • 8/3/2019 CS10 Coursewares

    53/290

    C++C++ forfor

    Engineers and ScientistsEngineers and Scientists

    Second EditionSecond Edition

    Chapter 2Problem Solving Using C++

  • 8/3/2019 CS10 Coursewares

    54/290

    C++ for Engineers and Scientists, Second Edition 54

    ObjectivesObjectives

    Introduction to C++

    Programming Style

    Data Types

    Arithmetic Operations

    Variables and Declaration Statements

  • 8/3/2019 CS10 Coursewares

    55/290

    C++ for Engineers and Scientists, Second Edition 55

    Objectives (continued)Objectives (continued)

    Applying the Software Development Procedure

    Applications

    Common Programming Errors

  • 8/3/2019 CS10 Coursewares

    56/290

    C++ for Engineers and Scientists, Second Edition 56

    Introduction to C++Introduction to C++

    Modular Program: a program consisting ofinterrelated segments arranged in a logical andunderstandable form

    Easier to develop, correct, and modify than otherkinds of programs

    Module: a small segment which is designed toperform a specific task

    A group of modules is used to construct amodular program

  • 8/3/2019 CS10 Coursewares

    57/290

    C++ for Engineers and Scientists, Second Edition 57

    Introduction to C++ (continued)Introduction to C++ (continued)

    Figure 2.1 A well-designed program is built using

    modules.

  • 8/3/2019 CS10 Coursewares

    58/290

    C++ for Engineers and Scientists, Second Edition 58

    Introduction to C++ (continued)Introduction to C++ (continued)

    Modules in C++ can be classes or functions

    Function: accepts an input and produces an

    output by processing the input in some fashion A functions processing is encapsulated and

    hidden within the function

  • 8/3/2019 CS10 Coursewares

    59/290

    C++ for Engineers and Scientists, Second Edition 59

    Introduction to C++ (continued)Introduction to C++ (continued)

    Figure 2.2 A multiplying function.

  • 8/3/2019 CS10 Coursewares

    60/290

    C++ for Engineers and Scientists, Second Edition 60

    Introduction to C++ (continued)Introduction to C++ (continued)

    Class: contains both data and functions used

    to manipulate the data

    Function: encapsulates a set of operations,while a class encapsulates data plus one or

    more sets of operations

    Identifier: a name given to an element of the

    language, such as a class or function

  • 8/3/2019 CS10 Coursewares

    61/290

    C++ for Engineers and Scientists, Second Edition 61

    Introduction to C++ (continued)Introduction to C++ (continued)

    Rules for forming identifier names:

    First character must be a letter or underscore

    Only letters, digits, or underscores may followthe initial letter (no blanks allowed)

    Keywords cannot be used as identifiers

    Max length of an identifier = 1024 characters

    Use underscores to separate multiple words ina name, or capitalize the first letter of eachword

  • 8/3/2019 CS10 Coursewares

    62/290

    C++ for Engineers and Scientists, Second Edition 62

    Introduction to C++ (continued)Introduction to C++ (continued)

    Keywords

    Keyword: a reserved name that represents a

    built-in object or function of the language

  • 8/3/2019 CS10 Coursewares

    63/290

    C++ for Engineers and Scientists, Second Edition 63

    Introduction to C++ (continued)Introduction to C++ (continued)

    Examples of valid C++ identifiers:

    degToRad intersect addNums

    slope bessell multTwo

    findMax density

    Examples of invalid C++ identifiers:

    1AB3 (begins with a number)

    E*6 (contains a special character)

    while (this is a keyword)

  • 8/3/2019 CS10 Coursewares

    64/290

    C++ for Engineers and Scientists, Second Edition 64

    Introduction to C++ (continued)Introduction to C++ (continued)

    Function names

    Require a set of parentheses at the end

    Can use mixed upper and lower case

    Should be meaningful, or be a mnemonic

    Mnemonic: a word designed as a memory aid

    Examples of function names:

    easy() c3 po() r2d2() theForce()

    Note that C++ is a case-sensitive language!

  • 8/3/2019 CS10 Coursewares

    65/290

    C++ for Engineers and Scientists, Second Edition 65

    Introduction to C++:Introduction to C++:TheThe main()main() FunctionFunction

    Overall structure of a C++ program containsone function named main(), called the driver

    function All other functions are invoked from main()

  • 8/3/2019 CS10 Coursewares

    66/290

    C++ for Engineers and Scientists, Second Edition 66

    Introduction to C++:Introduction to C++:

    TheThe main()main() FunctionFunction (continued)(continued)

    Figure 2.3 The main() function directs all other functions.

  • 8/3/2019 CS10 Coursewares

    67/290

    C++ for Engineers and Scientists, Second Edition 67

    Introduction to C++ : TheIntroduction to C++ : The main()main()

    FunctionFunction (continued)(continued)

    Function header line: the first line of afunction, which contains

    The type of data returned by the function (if any)

    The name of the function

    The type of data that must be passed into thefunction when it is invoked (if any)

    Arguments: the data passed into a function Function body: the statements inside afunction (enclosed in braces)

  • 8/3/2019 CS10 Coursewares

    68/290

    C++ for Engineers and Scientists, Second Edition 68

    Introduction to C++:Introduction to C++:

    TheThe main()main() FunctionFunction (continued)(continued)

    Each statement inside the function must be

    terminated with a semicolon

    return: a keyword causing the appropriatevalue to be returned from the function

    return 0 in the main() function causes the

    program to end

  • 8/3/2019 CS10 Coursewares

    69/290

  • 8/3/2019 CS10 Coursewares

    70/290

    C++ for Engineers and Scientists, Second Edition 70

    Introduction to C++: TheIntroduction to C++: The coutcout ObjectObject

    cout object: an output object that sends datato a standard output display device

  • 8/3/2019 CS10 Coursewares

    71/290

    C++ for Engineers and Scientists, Second Edition 71

    Introduction to C++: TheIntroduction to C++: The coutcout ObjectObject

    (continued)(continued)

    Preprocessor command: starts with a #;causes an action before the source code iscompiled into machine code

    #include : causes the namedfile to be inserted into the source code

    C++ provides a standard library with many pre-written classes that can be included

    Header files: files included at the head (top) ofa C++ program

  • 8/3/2019 CS10 Coursewares

    72/290

    C++ for Engineers and Scientists, Second Edition 72

    Introduction to C++ : TheIntroduction to C++ : The coutcout ObjectObject

    (continued)(continued)

    usingnamespace :

    indicates where header file is located

    Namespaces qualify a name; a function name

    in your class can be the same as one used in astandard library class

    String: any combination of letters, numbers,

    and special characters enclosed in double

    quotes (a delimiter)

    Delimiter: a symbol that marks the beginning

    and ending of a string; not part of the string

  • 8/3/2019 CS10 Coursewares

    73/290

    C++ for Engineers and Scientists, Second Edition 73

    Introduction to C++ : TheIntroduction to C++ : The coutcout ObjectObject

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    74/290

    C++ for Engineers and Scientists, Second Edition 74

    Introduction to C++ : TheIntroduction to C++ : The coutcout ObjectObject

    (continued)(continued)

    Escape sequence: one or more characterspreceded by a backslash, \

  • 8/3/2019 CS10 Coursewares

    75/290

    C++ for Engineers and Scientists, Second Edition 75

    Programming StyleProgramming Style

    Although more than one C++ statement can be

    on a single line, good style calls for one

    statement per line

    Opening and closing braces {} for the functionbody should each be on separate lines

    Statements in the function body should be

    indented

  • 8/3/2019 CS10 Coursewares

    76/290

    C++ for Engineers and Scientists, Second Edition 76

    Programming Style: CommentsProgramming Style: Comments

    Comments: explanatory remarks in the source

    code added by the programmer

    Line comment: begins with // and continues

    to the end of the line

    Line comment can be on a line by itself, or at the

    end of a line of code

    Line comment cannot be longer than one line

  • 8/3/2019 CS10 Coursewares

    77/290

    C++ for Engineers and Scientists, Second Edition 77

    Programming Style: CommentsProgramming Style: Comments

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    78/290

    C++ for Engineers and Scientists, Second Edition 78

    Programming Style: CommentsProgramming Style: Comments

    (continued)(continued)

    Block Comment: a comment that spans across

    two or more lines

    Block comment begins with /* and ends with */

    Example:

    /* Thisisablockcommentthat

    spans

    acrossthreelines */

  • 8/3/2019 CS10 Coursewares

    79/290

    C++ for Engineers and Scientists, Second Edition 79

    Data TypesData Types

    Data type: a set of values and the operations

    that can be applied to these values

    Two fundamental C++ data groupings:

    Class data type (a class): created by the

    programmer

    Built-in data type (primitive type): part of the

    C++ compiler

  • 8/3/2019 CS10 Coursewares

    80/290

    C++ for Engineers and Scientists, Second Edition 80

    Data Types (continued)Data Types (continued)

    Figure 2.7 Built-in data types.

  • 8/3/2019 CS10 Coursewares

    81/290

    C++ for Engineers and Scientists, Second Edition 81

    Data Types (continued)Data Types (continued)

    Literal (constant): an actual value

    Examples:

    3.6 //numericliteralHello //stringliteral

    Integer: a whole number

    C++ has 9 built-in integer data types, providing

    differing amounts of storage (compiler

    dependent)

  • 8/3/2019 CS10 Coursewares

    82/290

    C++ for Engineers and Scientists, Second Edition 82

    Data Types: Integer (continued)Data Types: Integer (continued)

  • 8/3/2019 CS10 Coursewares

    83/290

    C++ for Engineers and Scientists, Second Edition 83

    Data Types: Integer (continued)Data Types: Integer (continued)

    int data type: whole numbers, optionally with+ or sign

    Example: 2

    char data type: individual character; any letter,digit, or special character enclosed in singlequotes

    Example: A

    Character values are usually stored in ASCIIcode

  • 8/3/2019 CS10 Coursewares

    84/290

    C++ for Engineers and Scientists, Second Edition 84

    Data Types: Integer (continued)Data Types: Integer (continued)

    Figure 2.9 The letters BARTER stored inside a computer.

  • 8/3/2019 CS10 Coursewares

    85/290

    C++ for Engineers and Scientists, Second Edition 85

    Data Types: Integer (continued)Data Types: Integer (continued)

    Escape character: the backslash, \; indicates

    an escape sequence

    Escape sequence: tells compiler to treat thefollowing characters as special instruction

    codes

    Data Types: Integer (continued)Data Types: Integer (continued)

  • 8/3/2019 CS10 Coursewares

    86/290

    C++ for Engineers and Scientists, Second Edition 86

    Data Types: Integer (continued)Data Types: Integer (continued)

    Escape sequences

  • 8/3/2019 CS10 Coursewares

    87/290

    C++ for Engineers and Scientists, Second Edition 87

    Data Types: Integer (continued)Data Types: Integer (continued)

    bool data type: represents Boolean (logical)

    data; restricted to two values: true orfalse

    sizeof operator: shows the number of bytes

    used to store values of any data type

    Values returned by sizeof are compiler

    dependent

  • 8/3/2019 CS10 Coursewares

    88/290

    C++ for Engineers and Scientists, Second Edition 88

    Data Types: Integer (continued)Data Types: Integer (continued)

  • 8/3/2019 CS10 Coursewares

    89/290

    C++ for Engineers and Scientists, Second Edition 89

    Data Types: Integer (continued)Data Types: Integer (continued)

    Signed data type: one that permits negative,

    positive, and zero values

    Unsigned data type: permits only positive andzero values

    An unsigned data type provides essentially

    double the range of its signed counterpart

  • 8/3/2019 CS10 Coursewares

    90/290

    C++ for Engineers and Scientists, Second Edition 90

    Data Types: Integer (continued)Data Types: Integer (continued)

    Signed and unsigned integer data types

  • 8/3/2019 CS10 Coursewares

    91/290

    C++ for Engineers and Scientists, Second Edition 91

    Data Types: FloatingData Types: Floating--Point TypesPoint Types

    Floating-point number (real number): zero orany positive or negative number containing adecimal point

    Examples: +10.625 5. -6.2 No special characters are allowed

    Three floating-point data types in C++:

    float(single precision)

    double(double precision) longdouble

    D t T Fl tiD t T Fl ti P i t TP i t T

  • 8/3/2019 CS10 Coursewares

    92/290

    C++ for Engineers and Scientists, Second Edition 92

    Data Types: FloatingData Types: Floating--Point TypesPoint Types

    (continued)(continued)

    D t T Fl tiD t T Fl ti P i t TP i t T

  • 8/3/2019 CS10 Coursewares

    93/290

    C++ for Engineers and Scientists, Second Edition 93

    Data Types: FloatingData Types: Floating--Point TypesPoint Types

    (continued)(continued)

    float literal: append an f orF to the number

    longdoubleliteral: append an l orL to the

    number

    Examples:

    9.234 //adoubleliteral

    9.234F //afloatliteral

    9.234L //alongdoubleliteral

  • 8/3/2019 CS10 Coursewares

    94/290

    C++ for Engineers and Scientists, Second Edition 94

    Data Types: Exponential NotationData Types: Exponential Notation

    Floating point numbers can be written in

    exponential notation, where e stands for

    exponent

  • 8/3/2019 CS10 Coursewares

    95/290

    C++ for Engineers and Scientists, Second Edition 95

    Arithmetic OperationsArithmetic Operations

    C++ supports addition, subtraction,

    multiplication, division, and modulus division

    Different data types can be used in the same

    arithmetic expression

    Arithmetic operators are binary operators

    Binary operators: require two operands

  • 8/3/2019 CS10 Coursewares

    96/290

    C++ for Engineers and Scientists, Second Edition 96

    Arithmetic Operations (continued)Arithmetic Operations (continued)

    Operation Operator

    Addition +

    Subtraction -

    Multiplication *

    Division /

    Modulus division %

  • 8/3/2019 CS10 Coursewares

    97/290

    C++ for Engineers and Scientists, Second Edition 97

    Arithmetic Operations (continued)Arithmetic Operations (continued)

    Arithmetic Operations:Arithmetic Operations:

  • 8/3/2019 CS10 Coursewares

    98/290

    C++ for Engineers and Scientists, Second Edition 98

    Arithmetic Operations:Arithmetic Operations:

    Expression TypesExpression Types

    Expression: any combination of operators and

    operands that can be evaluated to yield a value

    If all operands are the same data type, the

    expression is named by the data type used(integer expression, floating-point expression,

    etc.)

    Mixed-mode expression: contains integer and

    floating-point operands; yields a double-

    precision value

    Arithmetic Operations:Arithmetic Operations:

  • 8/3/2019 CS10 Coursewares

    99/290

    C++ for Engineers and Scientists, Second Edition 99

    Arithmetic Operations:Arithmetic Operations:

    Integer DivisionInteger Division

    Integer division: yields an integer result

    Any fractional remainders are dropped

    (truncated)

    Example: 15/2 yields 7

    Modulus (remainder) operator: returns only the

    remainder

    Example: 9 % 4 yields 1

  • 8/3/2019 CS10 Coursewares

    100/290

    A ith ti O tiA ith ti O ti

  • 8/3/2019 CS10 Coursewares

    101/290

    C++ for Engineers and Scientists, Second Edition 101

    Arithmetic OperationsArithmetic OperationsSummary of OperatorsSummary of Operators

    Arithmetic Operations:Arithmetic Operations:

  • 8/3/2019 CS10 Coursewares

    102/290

    C++ for Engineers and Scientists, Second Edition 102

    Arithmetic Operations:Arithmetic Operations:

    Operator Precedence & AssociativityOperator Precedence & Associativity

    Rules for writing arithmetic expressions:

    Never place two consecutive binary arithmeticoperators side by side

    Use parentheses to form groupings; contentswithin parentheses are evaluated first

    You may nest parentheses within otherparentheses; evaluated from innermost tooutermost

    Use the * operator for multiplication, notparentheses

    Arithmetic Operations:Arithmetic Operations:

  • 8/3/2019 CS10 Coursewares

    103/290

    C++ for Engineers and Scientists, Second Edition 103

    Operator Precedence & AssociativityOperator Precedence & Associativity

    (continued)(continued) Expressions with multiple operators are

    evaluated by precedence of operators:

    All negations occur first

    Multiplication, division, and modulus are next,

    from left to right

    Addition and subtraction are last, from left to

    right

    Arithmetic Operations:Arithmetic Operations:

  • 8/3/2019 CS10 Coursewares

    104/290

    C++ for Engineers and Scientists, Second Edition 104

    Operator Precedence & AssociativityOperator Precedence & Associativity

    (continued)(continued) Associativity: the order in which operators of

    the same precedence are evaluated

  • 8/3/2019 CS10 Coursewares

    105/290

    C++ for Engineers and Scientists, Second Edition 105

    Variables and Declaration StatementsVariables and Declaration Statements

    Variable: symbolic identifier for a memory

    address where data can be held

    Use identifier naming rules for variable names

    Figure 2.11

    Naming

    storagelocations.

    Variables and Declaration StatementsVariables and Declaration Statements

  • 8/3/2019 CS10 Coursewares

    106/290

    C++ for Engineers and Scientists, Second Edition 106

    Variables and Declaration StatementsVariables and Declaration Statements

    (continued)(continued)

    Assignment statement: used to store a value

    into a variable

    Value of the expression on the right side of the= is assigned to the memory location of the

    variable on the left side of the =

    Examples:

    num1 = 45;num2 = 12;

    total=num1 +num2;

    Variables and Declaration StatementsVariables and Declaration Statements

  • 8/3/2019 CS10 Coursewares

    107/290

    C++ for Engineers and Scientists, Second Edition 107

    Variables and Declaration StatementsVariables and Declaration Statements

    (continued)(continued)

    Declaration statement: specifies the data typeand identifier of a variable; sets up the memorylocation

    Syntax: ;

    Data type is any valid C++ data type

    Example: intsum;

    Declarations may be used anywhere in a

    function; usually grouped at the opening brace

  • 8/3/2019 CS10 Coursewares

    108/290

    Variables and Declaration StatementsVariables and Declaration Statements

  • 8/3/2019 CS10 Coursewares

    109/290

    C++ for Engineers and Scientists, Second Edition 109

    Variables and Declaration StatementsVariables and Declaration Statements

    (continued)(continued)

    Variables and Declaration StatementsVariables and Declaration Statements

  • 8/3/2019 CS10 Coursewares

    110/290

    C++ for Engineers and Scientists, Second Edition 110

    Variables and Declaration StatementsVariables and Declaration Statements

    (continued)(continued)

    Declaring a variable causes memory to be

    allocated based on the data type

    Figure 2.12b Defining the floating-point variablenamed slope.

    Variables and Declaration StatementsVariables and Declaration Statements

  • 8/3/2019 CS10 Coursewares

    111/290

    C++ for Engineers and Scientists, Second Edition 111

    Variables and Declaration StatementsVariables and Declaration Statements

    (continued)(continued)

    Definition statement: a declaration that causesthe computer to allocate storage for the variable

    Three items associated with each variable:

    Data type Actual value stored in the variable (its contents)

    Memory address of the variable

    Address operator (&) provides the variables

    address

    Variables and Declaration StatementsVariables and Declaration Statements

  • 8/3/2019 CS10 Coursewares

    112/290

    C++ for Engineers and Scientists, Second Edition 112

    Variables and Declaration StatementsVariables and Declaration Statements

    (continued)(continued)

    Applying the SoftwareApplying the Software

  • 8/3/2019 CS10 Coursewares

    113/290

    C++ for Engineers and Scientists, Second Edition 113

    Applying the SoftwareApplying the Software

    Development ProcedureDevelopment Procedure

    Step 1: Analyze the problem

    Understand the desired outputs

    Determine the required inputs Step 2: Develop a solution

    Determine the algorithms to be used

    Use top-down approach to design

    Step 3: Code the solution

    Step 4: Test and correct the program

    Applications: Radar Speed TrapApplications: Radar Speed Trap

  • 8/3/2019 CS10 Coursewares

    114/290

    C++ for Engineers and Scientists, Second Edition 114

    Applications: Radar Speed TrapApplications: Radar Speed Trap

    Step 1: Analyze the Problem

    Output: speed of the car

    Inputs: emitted frequency and receivedfrequency

    Step 2: Develop a Solution Algorithm:

    Assign values to f0 and f1 Calculate and display speed

    Step 3: Code the Solution Step 4: Test and Correct the Program

    Applications: Radar Speed TrapApplications: Radar Speed Trap

  • 8/3/2019 CS10 Coursewares

    115/290

    C++ for Engineers and Scientists, Second Edition 115

    Applications: Radar Speed TrapApplications: Radar Speed Trap

    (continued)(continued)

    Applications:Applications:

  • 8/3/2019 CS10 Coursewares

    116/290

    C++ for Engineers and Scientists, Second Edition 116

    Applications:Applications:

    Telephone Switching NetworksTelephone Switching Networks

    Number of lines required for a directly

    connected network:

    Figure 2.17 Directly connecting four telephones.

    Applications: Telephone SwitchingApplications: Telephone Switching

  • 8/3/2019 CS10 Coursewares

    117/290

    C++ for Engineers and Scientists, Second Edition 117

    Applications: Telephone SwitchingApplications: Telephone Switching

    Networks (continued)Networks (continued)

    Step 1: Analyze the Problem

    Outputs: number of direct lines for 100 phones,

    and additional number of lines to add 10 more

    phones

    Inputs: number of telephones (n)

    Step 2: Develop a Solution

    Calculate total number of lines for 100subscribers

    Applications: Telephone SwitchingApplications: Telephone Switching

  • 8/3/2019 CS10 Coursewares

    118/290

    C++ for Engineers and Scientists, Second Edition 118

    Applications: Telephone SwitchingApplications: Telephone Switching

    Networks (continued)Networks (continued)

    Step 2: Develop a Solution (continued)

    Calculate total number of lines for 110

    subscribers

    Subtract to get additional lines needed

    Display number of lines for 100 subscribers

    Display number of additional lines needed

    Step 3: Code the Solution Step 4: Test and Correct the Program

  • 8/3/2019 CS10 Coursewares

    119/290

    C P i EC P i E

  • 8/3/2019 CS10 Coursewares

    120/290

    C++ for Engineers and Scientists, Second Edition 120

    Common Programming ErrorsCommon Programming Errors

    Missing parentheses aftermain

    Missing or incorrect braces around function

    body Misspelling a reserved word

    Missing ending double quotes on string literal

    Missing semicolon at end of statement

    Common Programming ErrorsCommon Programming Errors

  • 8/3/2019 CS10 Coursewares

    121/290

    C++ for Engineers and Scientists, Second Edition 121

    Common Programming ErrorsCommon Programming Errors

    (continued)(continued)

    Adding a semicolon at end of#include

    statement

    Missing \n to indicate new line Substituting letter O for zero and vice versa

    Failing to declare all variables

    Storing incorrect data type into a variable

    Common Programming ErrorsCommon Programming Errors

  • 8/3/2019 CS10 Coursewares

    122/290

    C++ for Engineers and Scientists, Second Edition 122

    Common Programming ErrorsCommon Programming Errors

    (continued)(continued)

    Attempting to use a variable with no value

    Dividing integer values incorrectly

    Mixing data types in the same expression

    SS

  • 8/3/2019 CS10 Coursewares

    123/290

    C++ for Engineers and Scientists, Second Edition 123

    SummarySummary

    C++ program contains one or more functions,one of which must be called main()

    All C++ statements must be terminated by asemicolon

    Data types include int, float, bool, char

    cout object can be used to display data

    cout object requires the preprocessorcommand #include

    S ( ti d)S ( ti d)

  • 8/3/2019 CS10 Coursewares

    124/290

    C++ for Engineers and Scientists, Second Edition 124

    Summary (continued)Summary (continued)

    Variables must be declared with their data type

    A variable can be used only after it has been

    declared Variables may be initialized when declared

    Definition statement causes computer to

    allocate memory for a variable

    sizeof() operator yields the amount ofstorage reserved for a variable

  • 8/3/2019 CS10 Coursewares

    125/290

    Objecti esObjecti es

  • 8/3/2019 CS10 Coursewares

    126/290

    C++ for Engineers and Scientists, Second Edition 126

    ObjectivesObjectives

    Assignment Operations

    Formatting Numbers for Program Output

    Using Mathematical Library Functions Program Input Using the cin Object

    Symbolic Constants

    Objectives (continued)Objectives (continued)

  • 8/3/2019 CS10 Coursewares

    127/290

    C++ for Engineers and Scientists, Second Edition 127

    Objectives (continued)Objectives (continued)

    Applications

    Common Programming Errors

    A Closer Look: Programming Errors

    Assignment OperationsAssignment Operations

  • 8/3/2019 CS10 Coursewares

    128/290

    C++ for Engineers and Scientists, Second Edition 128

    Assignment OperationsAssignment Operations

    Assignment Statement: assigns the value of

    the expression on the right side of the = to the

    variable on the left side of the =

    Another assignment statement using the same

    variable will overwrite the previous value with

    the new value

    Examples:slope= 3.7;

    slope= 6.28;

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    129/290

    C++ for Engineers and Scientists, Second Edition 129

    Assignment Operations (continued)Assignment Operations (continued)

    Right side of an assignment statement maycontain any expression that can be evaluated toa value

    Examples:

    newtotal= 18.3 +total;

    taxes= .06*amount;

    average=sum/items;

    Only one variable can be on the left side of anassignment statement

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    130/290

    C++ for Engineers and Scientists, Second Edition 130

    Assignment Operations (continued)Assignment Operations (continued)

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    131/290

    C++ for Engineers and Scientists, Second Edition 131

    Assignment Operations (continued)Assignment Operations (continued)

    Assignment operator: the = sign

    C++ statement: any expression terminated by

    a semicolon

    Multiple assignments in the same expressionare possible

    Example:

    a=b=c= 25;

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    132/290

    C++ for Engineers and Scientists, Second Edition 132

    Assignment Operations (continued)Assignment Operations (continued)

    Coercion: forcing a data value to another data

    type

    Value of the expression on the right side of anassignment statement will be coerced

    (converted) to the data type of the variable on

    the left side during evaluation

    Variable on the left side may also be used onthe right side of an assignment statement

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    133/290

    C++ for Engineers and Scientists, Second Edition 133

    Assignment Operations (continued)Assignment Operations (continued)

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    134/290

    C++ for Engineers and Scientists, Second Edition 134

    Assignment Operations (continued)Assignment Operations (continued)

    Additional assignment operators provide shortcuts: +=, -=, *=, /=, %=

    Example:

    sum=sum+ 10;

    is equivalent to: sum+= 10;

    price *=rate+1;

    is equivalent to:price=price * (rate+ 1);

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    135/290

    C++ for Engineers and Scientists, Second Edition 135

    g p ( )g p ( )

    Accumulation statement: has the effect ofaccumulating, or totaling

    Syntax:

    variable= variable+newValue;

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    136/290

    C++ for Engineers and Scientists, Second Edition 136

    Assignment Operations (continued)Assignment Operations (continued)

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    137/290

    C++ for Engineers and Scientists, Second Edition 137

    Assignment Operations (continued)Assignment Operations (continued)

    Counting statement: adds a fixed value to thevariables current value

    Syntax:

    variable= variable+fixedNumber;

    Example:

    i=i+ 1;

    count=count+ 1;

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    138/290

    C++ for Engineers and Scientists, Second Edition 138

    Assignment Operations (continued)Assignment Operations (continued)

    Increment operator++: unary operator for thespecial case when a variable is increased by 1

    Prefix increment operatorappears before the

    variableExample: ++i

    Postfix increment operatorappears after thevariable

    Example: i++

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    139/290

    C++ for Engineers and Scientists, Second Edition 139

    Assignment Operations (continued)Assignment Operations (continued)

    Example: k=++n; //prefixincrement

    is equivalent to

    n=n+ 1; //incrementnfirst

    k=n; //assignns valuetok

    Example: k=n++; //postfixincrement

    is equivalent to

    k=n; //assignns valuetokn=n+ 1; //andthenincrementn

    Assignment Operations (continued)Assignment Operations (continued)

  • 8/3/2019 CS10 Coursewares

    140/290

    C++ for Engineers and Scientists, Second Edition 140

    Assignment Operations (continued)Assignment Operations (continued)

    Decrement operator--: unary operator for

    the special case when a variable is decreased

    by 1

    Prefix decrement operatorappears before the

    variable

    Example: --i;

    Postfix decrement operatorappears after thevariable

    Example: i--;

    Formatting NumbersFormatting Numbers

  • 8/3/2019 CS10 Coursewares

    141/290

    C++ for Engineers and Scientists, Second Edition 141

    for Program Outputfor Program Output

    Proper output formatting contributes to ease of

    use and user satisfaction

    cout with stream manipulators can control

    output formatting

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    142/290

    C++ for Engineers and Scientists, Second Edition 142

    Program Output (continued)Program Output (continued)

    Table 3.1 Commonly Used Stream Manipulators

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    143/290

    C++ for Engineers and Scientists, Second Edition 143

    Program Output (continued)Program Output (continued)

    Table 3.1 Commonly Used Stream Manipulators(continued)

  • 8/3/2019 CS10 Coursewares

    144/290

    Formatting Numbers forFormatting Numbers for

  • 8/3/2019 CS10 Coursewares

    145/290

    C++ for Engineers and Scientists, Second Edition 145

    Program Output (continued)Program Output (continued)

    The field width manipulator must be includedfor each value in the data stream sent to cout

    Other manipulators remain in effect until they

    are changed

    iomanip header file must be included to use

    manipulators requiring arguments

    Formatting Numbers forFormatting Numbers for

    P O ( i d)P O ( i d)

  • 8/3/2019 CS10 Coursewares

    146/290

    C++ for Engineers and Scientists, Second Edition 146

    Program Output (continued)Program Output (continued)

    Formatting floating-point numbers requires

    three field-width manipulators to

    Set the total width of the display

    Force a decimal place

    Set the number of significant digits after the

    decimal point

    Example:

    produces this output:

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    147/290

    C++ for Engineers and Scientists, Second Edition 147

    Program Output (continued)Program Output (continued)

    setprecision: sets the number of digits after

    the decimal point if a decimal point has been

    explicitly forced; otherwise, it sets the total

    number of displayed digits If the field width is too small, cout ignores the

    setwmanipulator setting and allocates

    enough space for printing

    Ifsetprecision setting is too small, thefractional part of the value is rounded to the

    specified number of decimal places

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    148/290

    C++ for Engineers and Scientists, Second Edition 148

    Program Output (continued)Program Output (continued)

    Ifsetprecision value is too large, thefractional value is displayed with its current size

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    149/290

    C++ for Engineers and Scientists, Second Edition 149

    Program Output (continued)Program Output (continued)

    Table 3.2 Effect of Format Manipulators

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    150/290

    C++ for Engineers and Scientists, Second Edition 150

    Program Output (continued)Program Output (continued)

    Table 3.2 Effect of Format Manipulators (continued)

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    151/290

    C++ for Engineers and Scientists, Second Edition 151

    Program Output (continued)Program Output (continued)

    setiosflags manipulator: allows additional

    formatting:

    Right or left justification

    Fixed display with 6 decimal places Scientific notation with exponential display

    Display of a leading + sign

    Parameterized manipulator: one which

    requires arguments, or parameters

  • 8/3/2019 CS10 Coursewares

    152/290

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    153/290

    C++ for Engineers and Scientists, Second Edition 153

    Program Output (continued)Program Output (continued)

    Formatting Numbers forFormatting Numbers for

    P O t t ( ti d)P O t t ( ti d)

  • 8/3/2019 CS10 Coursewares

    154/290

    C++ for Engineers and Scientists, Second Edition 154

    Program Output (continued)Program Output (continued)

    To designate an octal integer constant, use a

    leading zero

    To designate a hexadecimal integer constant,

    use a leading 0x Manipulators affect only output; the value

    stored internally does not change

    Formatting Numbers for ProgramFormatting Numbers for Program

    O tp t (contin ed)O tp t (contin ed)

  • 8/3/2019 CS10 Coursewares

    155/290

    C++ for Engineers and Scientists, Second Edition 155

    Output (continued)Output (continued)

    Formatting Numbers forFormatting Numbers for

    Program Output (continued)Program Output (continued)

  • 8/3/2019 CS10 Coursewares

    156/290

    C++ for Engineers and Scientists, Second Edition 156

    Program Output (continued)Program Output (continued)

    Manipulators can also be set using theostreamclass methods

    Separate the cout object name from the

    method name with a periodExample:

    cout.precision(2)

    Formatting Numbers forFormatting Numbers for

    Program Output (continued)Program Output (continued)

  • 8/3/2019 CS10 Coursewares

    157/290

    C++ for Engineers and Scientists, Second Edition 157

    Program Output (continued)Program Output (continued)

    Table 3.4 ostreamClass Methods

  • 8/3/2019 CS10 Coursewares

    158/290

    Using Mathematical Library FunctionsUsing Mathematical Library Functions

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    159/290

    C++ for Engineers and Scientists, Second Edition 159

    (continued)(continued)

    Table 3.5 Common C++ Functions

    Using Mathematical Library FunctionsUsing Mathematical Library Functions

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    160/290

    C++ for Engineers and Scientists, Second Edition 160

    (continued)(continued)

    To use a math function, give its name and pass

    the input arguments within parentheses

    Expressions that can be evaluated to a value

    can be passed as arguments

    Using Mathematical Library FunctionsUsing Mathematical Library Functions

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    161/290

    C++ for Engineers and Scientists, Second Edition 161

    (continued)(continued)

    Using Mathematical Library FunctionsUsing Mathematical Library Functions

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    162/290

    C++ for Engineers and Scientists, Second Edition 162

    (continued)(continued)

    Function calls can be nested

    Example: sqrt(sin(abs(theta)))

    Cast operator: a unary operator that forces the

    data to the desired data type Compile-time cast

    Syntax: dataType(expression)

    Example: int(a+b)

    Using Mathematical Library FunctionsUsing Mathematical Library Functions

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    163/290

    C++ for Engineers and Scientists, Second Edition 163

    (continued)(continued)

    Run-time cast: the requested conversion is

    checked at run time and applied if valid

    Syntax:

    staticCast(expression)Example:

    staticCast(a*b)

    Program Input Using theProgram Input Using the cincin ObjectObject

  • 8/3/2019 CS10 Coursewares

    164/290

    C++ for Engineers and Scientists, Second Edition 164

    cin Object: allows data entry to a running

    program

    Use of the cin object causes the program to

    wait for input from the keyboard When keyboard entry is complete, the program

    resumes execution, using the entered data

    An output statement preceding the cin object

    statement provides a prompt to the user

    Program Input Using theProgram Input Using the cincin ObjectObject

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    165/290

    C++ for Engineers and Scientists, Second Edition 165

    (continued)(continued)

    Program Input Using theProgram Input Using the cincin ObjectObject

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    166/290

    C++ for Engineers and Scientists, Second Edition 166

    (continued)(continued)

    cincan accept multiple input values to be

    stored in different variables

    Multiple numeric input values must be

    separated by spacesExample:

    cin>>num1 >>num2

    with keyboard entry: 0.052 245.79

    Program Input Using theProgram Input Using the cincin ObjectObject

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    167/290

    C++ for Engineers and Scientists, Second Edition 167

    (continued)(continued)

    Program Input Using theProgram Input Using the cincin ObjectObject

    ( ti d)( ti d)

  • 8/3/2019 CS10 Coursewares

    168/290

    C++ for Engineers and Scientists, Second Edition 168

    (continued)(continued)

    User-input validation: the process of

    ensuring that data entered by the user matches

    the expected data type

    Robust program: one that detects and

    handles incorrect user entry

    Symbolic ConstantsSymbolic Constants

  • 8/3/2019 CS10 Coursewares

    169/290

    C++ for Engineers and Scientists, Second Edition 169

    Symbolic constant: a constant value that isdeclared with an identifier using the const

    keyword

    A constants value may not be changedExample:

    constint MAXNUM= 100;

    Good programming places statements inappropriate order

    Symbolic Constants (continued)Symbolic Constants (continued)

  • 8/3/2019 CS10 Coursewares

    170/290

    C++ for Engineers and Scientists, Second Edition 170

    Proper placement of statements:preprocessordirectives

    intmain()

    {

    symbolicconstants

    mainfunctiondeclarations

    otherexecutablestatements

    return value

    }

    ApplicationsApplications

  • 8/3/2019 CS10 Coursewares

    171/290

    C++ for Engineers and Scientists, Second Edition 171

    Acid Rain: develop a program to calculate the

    pH level of a substance based on user input of

    the concentration of hydronium ions

    Approximating the Exponential Function:develop a program that approximates ex

    Common Programming ErrorsCommon Programming Errors

  • 8/3/2019 CS10 Coursewares

    172/290

    C++ for Engineers and Scientists, Second Edition 172

    Failure to declare or initialize variables before

    use

    Failure to include the preprocessor statement

    when using a C++ preprogrammed library Passing the incorrect number or type of

    arguments to a function

    Applying increment or decrement operator to an

    expression instead of an individual variable

    Common Programming ErrorsCommon Programming Errors

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    173/290

    C++ for Engineers and Scientists, Second Edition 173

    (continued)(continued)

    Failure to separate all variables passed to cin

    with the extraction symbol >>

    Failure to test thoroughly

    Compiler-dependent evaluation whenincrement or decrement operators are used

    with variables that appear more than once in

    the same expression

    SummarySummary

  • 8/3/2019 CS10 Coursewares

    174/290

    C++ for Engineers and Scientists, Second Edition 174

    Expression: a sequence of one or more

    operands separated by operators

    Expressions are evaluated based on

    precedence and associativity Assignment operator: =

    Increment operator: ++

    Decrement operator: --

    Summary (continued)Summary (continued)

  • 8/3/2019 CS10 Coursewares

    175/290

    C++ for Engineers and Scientists, Second Edition 175

    Use #include for math functions

    Arguments to a function must be passed in the

    proper number, type, and order

    Functions may be included within largerexpressions

    cin object provides data input from a

    keyboard; program is suspended until the input

    arrives

    Summary (continued)Summary (continued)

  • 8/3/2019 CS10 Coursewares

    176/290

    C++ for Engineers and Scientists, Second Edition 176

    Use a prompt to alert the user to provide input

    Constants are named values that do not

    change

    A Closer Look: Programming ErrorsA Closer Look: Programming Errors

  • 8/3/2019 CS10 Coursewares

    177/290

    C++ for Engineers and Scientists, Second Edition 177

    Program errors may be detected in four ways:

    Before a program is compiled (desk checking)

    While it is being compiled (compile-time errors)

    While it is being run (run-time errors) While examining the output after completion

    Errors may be

    Typos in the source code

    Logic errors

    A Closer Look: Programming ErrorsA Closer Look: Programming Errors

  • 8/3/2019 CS10 Coursewares

    178/290

    C++ for Engineers and Scientists, Second Edition 178

    Logic errors: often difficult to detect, and difficult

    to find the source

    Program tracing: stepping through the

    program by hand or with a trace tool Debugger: program that allows the interruption

    of a running program to determine values of its

    variables at any point

  • 8/3/2019 CS10 Coursewares

    179/290

    C++C++ forfor

    Engineers and ScientistsEngineers and Scientists

    Second EditionSecond Edition

    Chapter 4Selection Structures

    ObjectivesObjectives

  • 8/3/2019 CS10 Coursewares

    180/290

    C++ for Engineers and Scientists, Second Edition 180

    Selection Criteria

    The if-then-else Statement

    Nested if Statements

    The switch Statement

    Applications

    Objectives (continued)Objectives (continued)

  • 8/3/2019 CS10 Coursewares

    181/290

    C++ for Engineers and Scientists, Second Edition 181

    Common Programming Errors

    A Closer Look at Program Testing

    Selection CriteriaSelection Criteria

  • 8/3/2019 CS10 Coursewares

    182/290

    C++ for Engineers and Scientists, Second Edition 182

    if-else statement: implements a decision

    structure for two alternatives

    Syntax:

    if (condition)

    statement executed if condition is true;

    else

    statement executed if condition is false;

    Selection Criteria (continued)Selection Criteria (continued)

  • 8/3/2019 CS10 Coursewares

    183/290

    C++ for Engineers and Scientists, Second Edition 183

    The condition is evaluated to its numerical

    value:

    A non-zero value is considered to be true

    A zero value is considered to be false The else portion is optional; it is executed only

    if the condition is false

    The condition may be any valid C++ expression

    Selection Criteria (continued)Selection Criteria (continued)

  • 8/3/2019 CS10 Coursewares

    184/290

    C++ for Engineers and Scientists, Second Edition 184

    Relational expression: compares two

    operands or expressions using relational

    operators

    Selection Criteria (continued)Selection Criteria (continued)

  • 8/3/2019 CS10 Coursewares

    185/290

    C++ for Engineers and Scientists, Second Edition 185

    Relational expressions are evaluated to a

    numerical value of 1 or 0 only:

    If the value is 1, the expression is true

    If the value is 0, the expression is false char values are automatically coerced to int

    values for comparison purposes

    Strings are compared on a character by

    character basis; the string with the first lowercharacter is considered smaller

    Selection Criteria (continued)Selection Criteria (continued)E l f t i i

  • 8/3/2019 CS10 Coursewares

    186/290

    C++ for Engineers and Scientists, Second Edition 186

    Examples of string comparisons:

    Selection Criteria (continued)Selection Criteria (continued)

  • 8/3/2019 CS10 Coursewares

    187/290

    C++ for Engineers and Scientists, Second Edition 187

    Logical operators

    AND (&&): condition is true only if both

    expressions are true

    OR (||): condition is true if either one or both of

    the expressions is true

    NOT (!): changes an expression to its opposite

    state; true becomes false, false becomes true

    Selection Criteria (continued)Selection Criteria (continued)

  • 8/3/2019 CS10 Coursewares

    188/290

    C++ for Engineers and Scientists, Second Edition 188

    Precedence and Associativity of Operators

  • 8/3/2019 CS10 Coursewares

    189/290

    TheThe ifif--elseelse StatementStatement

  • 8/3/2019 CS10 Coursewares

    190/290

    C++ for Engineers and Scientists, Second Edition 190

    if-else performs instructions based on theresult of a comparison

    Place statements on separate lines for readability

    Syntax:

    TheThe ifif--elseelse Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    191/290

    C++ for Engineers and Scientists, Second Edition 191

    Figure 4.2The if-else

    flowchart.

  • 8/3/2019 CS10 Coursewares

    192/290

    TheThe ifif--elseelse Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    193/290

    C++ for Engineers and Scientists, Second Edition 193

    Compound statement: a sequence of singlestatements contained between braces, creating ablock of statements

    Block of statements can be used anywhere that a

    single statement is legal Any variable declared within a block is usable only

    within that block

    Scope: the area within a program where a variable

    can be used; a variables scope is based on wherethe variable is declared

    TheThe ifif--elseelse Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    194/290

    C++ for Engineers and Scientists, Second Edition 194

    TheThe ifif--elseelse Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    195/290

    C++ for Engineers and Scientists, Second Edition 195

    One-way selection: anif statement without the

    optional else portion

    TheThe ifif--elseelse Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    196/290

    C++ for Engineers and Scientists, Second Edition 196

    Common problems with if-else statements:

    Misunderstanding what an expression is

    Using the assignment operator (=) instead of the

    relational operator (==)

    NestedNested ifif StatementsStatements

  • 8/3/2019 CS10 Coursewares

    197/290

    C++ for Engineers and Scientists, Second Edition 197

    if-else statement can contain any valid C++

    statement, including another if-else

    Nested if statement: an if-else statement

    completely contained within anotherif-else Use braces to block code, especially when

    innerifstatement does not have its ownelse

    NestedNested ifif Statements (continued)Statements (continued)

  • 8/3/2019 CS10 Coursewares

    198/290

    C++ for Engineers and Scientists, Second Edition 198

    Figure 4.5aif-else

    statement

    nested in anif.

    NestedNested ifif Statements (continued)Statements (continued)

  • 8/3/2019 CS10 Coursewares

    199/290

    C++ for Engineers and Scientists, Second Edition 199

    if-elsechain: a nested if statement

    occurring in the else clause of the outerif-else

    If any condition is true, the correspondingstatement is executed and the chain terminates

    Final else is only executed if no conditions

    were true; serves as a catch-all case

    if-else chain provides one selection from

    many possible alternatives

    NestedNested ifif Statements (continued)Statements (continued)

  • 8/3/2019 CS10 Coursewares

    200/290

    C++ for Engineers and Scientists, Second Edition 200

    Figure 4.5b if-else

    statement nested in anelse.

    General form of anif-elsechain.

    NestedNested ifif Statements (continued)Statements (continued)

  • 8/3/2019 CS10 Coursewares

    201/290

    C++ for Engineers and Scientists, Second Edition 201

    TheThe switchswitch StatementStatement

  • 8/3/2019 CS10 Coursewares

    202/290

    C++ for Engineers and Scientists, Second Edition 202

    switch statement: provides for one selectionfrom many alternatives

    switch keyword starts the statement; isfollowed by the expression to be evaluated

    case keyword identifies a value to be comparedto the switch expression; when a match isfound, statements in this case block areexecuted

    All further cases after a match is found areexecuted unless a break statement is found

    TheThe switchswitch Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    203/290

    C++ for Engineers and Scientists, Second Edition 203

    default case is executed if no other casevalue matches were found

    default case is optional

    TheThe switchswitch Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    204/290

    C++ for Engineers and Scientists, Second Edition 204

    TheThe switchswitch Statement (continued)Statement (continued)

  • 8/3/2019 CS10 Coursewares

    205/290

    C++ for Engineers and Scientists, Second Edition 205

    Common Programming ErrorsCommon Programming Errors

  • 8/3/2019 CS10 Coursewares

    206/290

    C++ for Engineers and Scientists, Second Edition 206

    Using the assignment operator (=) instead of

    the relational operator (==) for an equality test

    Assuming a structural problem with an if-else

    causes the error instead of focusing on the datavalue being tested

    Using nested if statements without braces to

    define the structure

    SummarySummary

  • 8/3/2019 CS10 Coursewares

    207/290

    C++ for Engineers and Scientists, Second Edition 207

    Relational expressions, or conditions, are used

    to compare operands

    If the relation expression is true, its value is 1;

    if false, its value is 0 Use logical operators && (AND), || (OR), and

    ! (NOT) to construct complex conditions

    if-else allows selection between two

    alternatives

    Summary (continued)Summary (continued)

  • 8/3/2019 CS10 Coursewares

    208/290

    C++ for Engineers and Scientists, Second Edition 208

    An if expression that evaluates to 0 is false; if

    non-zero, it is true

    if statements can be nested

    Chained if statement provides a multiwayselection

    Compound statement contains any number of

    individual statements enclosed in braces

    Summary (continued)Summary (continued)

  • 8/3/2019 CS10 Coursewares

    209/290

    C++ for Engineers and Scientists, Second Edition 209

    switch statement provides a multiwayselection

    switch expression is evaluated and compared

    to each case value; if a match is found,

    execution begins at that cases statements andcontinues unless a break is encountered

  • 8/3/2019 CS10 Coursewares

    210/290

    C++C++ forforEngineers and ScientistsEngineers and Scientists

    Second EditionSecond Edition

    Chapter 5

    Repetition Statements

    ObjectivesObjectives

  • 8/3/2019 CS10 Coursewares

    211/290

    C++ for Engineers and Scientists, Second Edition 211

    Basic Loop Structures

    while Loops

    Interactive while Loops

    for loops

    Loop Programming Techniques

    Objectives (continued)Objectives (continued)

  • 8/3/2019 CS10 Coursewares

    212/290

    C++ for Engineers and Scientists, Second Edition 212

    Nested Loops

    do while Loops

    Common Programming Errors

    Basic Loop StructuresBasic Loop Structures

  • 8/3/2019 CS10 Coursewares

    213/290

    C++ for Engineers and Scientists, Second Edition 213

    Repetition structure has four required elements:

    Repetition statement

    Condition to be evaluated

    Initial value for the condition

    Loop termination

    Repetition statements include

    while

    for dowhile

    Basic Loop Structures (continued)Basic Loop Structures (continued)

  • 8/3/2019 CS10 Coursewares

    214/290

    C++ for Engineers and Scientists, Second Edition 214

    The condition can be tested

    At the beginning: pretest orentrance-

    controlled loop

    At the end: posttest orexit-controlled loop

    Something in the loop body must cause the

    condition to change, to avoid an infinite loop,

    which never terminates

    whilewhile LoopsLoops

  • 8/3/2019 CS10 Coursewares

    215/290

    C++ for Engineers and Scientists, Second Edition 215

    while statement is used to create a whileloop

    Syntax: while (expression)

    statement;

    Statements following the expressions are

    executed as long as the expression condition

    remains true (evaluates to a non-zero value)

    whilewhile Loops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    216/290

    C++ for Engineers and Scientists, Second Edition 216

    Figure 5.3

    Anatomy of awhile loop.

    whilewhile Loops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    217/290

    C++ for Engineers and Scientists, Second Edition 217

    InteractiveInteractive whilewhileLoopsLoops

  • 8/3/2019 CS10 Coursewares

    218/290

    C++ for Engineers and Scientists, Second Edition 218

    Combining interactive data entry with thewhile statement provides for repetitive entry

    and accumulation of totals

    InteractiveInteractive whilewhileLoops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    219/290

    C++ for Engineers and Scientists, Second Edition 219

    InteractiveInteractive whilewhileLoops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    220/290

    C++ for Engineers and Scientists, Second Edition 220

    InteractiveInteractive whilewhileLoops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    221/290

    C++ for Engineers and Scientists, Second Edition 221

    break statement: forces an immediate break,or exit, from switch, while, for, and do-

    while statements

    break statement violates pure structuredprogramming, but is useful for breaking out of

    loops when an unusual condition is detected

    InteractiveInteractive whilewhileLoops (continued)Loops (continued)

    Example of a break statement:

  • 8/3/2019 CS10 Coursewares

    222/290

    C++ for Engineers and Scientists, Second Edition 222

    p

    InteractiveInteractive whilewhileLoops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    223/290

    C++ for Engineers and Scientists, Second Edition 223

    continue statement: applies to while, do-while, and for statements; causes the nextiteration of the loop to begin immediately

    continue statement is useful for skipping overdata that should not be processed in thisiteration, while staying within the loop

    Null statement: a semicolon with nothingpreceding it; a do-nothing statement required

    for syntax purposes only

    forfor LoopsLoops

  • 8/3/2019 CS10 Coursewares

    224/290

    C++ for Engineers and Scientists, Second Edition 224

    forstatement: a loop with a fixed countcondition that handles alteration of the condition

    Syntax:for (initializing list; expression; altering list)

    statement;

    Initializing list: sets the starting value of a

    counter

    Expression: contains the maximum or

    minimum value the counter can have;determines when the loop is finished

    forfor Loops (continued)Loops (continued)

    Altering list: provides the increment value that

  • 8/3/2019 CS10 Coursewares

    225/290

    C++ for Engineers and Scientists, Second Edition 225

    is added or subtracted from the counter in eachiteration of the loop

    If initializing list is missing, the counter initialvalue must be provided prior to entering the for

    loop If altering list is missing, the counter must be

    altered in the loop body

    Omitting the expression will result in an infinite

    loop

    forfor Loops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    226/290

    C++ for Engineers and Scientists, Second Edition 226

    forfor Loops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    227/290

    C++ for Engineers and Scientists, Second Edition 227

    Figure 5.7for loop

    flowchart.

    Loop Programming TechniquesLoop Programming Techniques

  • 8/3/2019 CS10 Coursewares

    228/290

    C++ for Engineers and Scientists, Second Edition 228

    These techniques are suitable for pretest loops(for and while):

    Interactive Input within a Loop

    Includes a cin statement within a while orfor

    loop Selection within a Loop

    Using a for orwhile loop to cycle through a setof values to select those values that meet somecriteria

    Loop Programming TechniquesLoop Programming Techniques

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    229/290

    C++ for Engineers and Scientists, Second Edition 229

    Loop Programming TechniquesLoop Programming Techniques

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    230/290

    C++ for Engineers and Scientists, Second Edition 230

    Evaluating Functions of One Variable

    Used for functions that must be evaluated over a

    range of values

    Noninteger increment values can be used

    Loop Programming TechniquesLoop Programming Techniques

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    231/290

    C++ for Engineers and Scientists, Second Edition 231

    Loop Programming TechniquesLoop Programming Techniques

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    232/290

    C++ for Engineers and Scientists, Second Edition 232

    Interactive Loop Control

    Variable is used to control the loop repetitions

    Provides more flexibility at run-time

    Loop Programming TechniquesLoop Programming Techniques

    (continued)(continued)

  • 8/3/2019 CS10 Coursewares

    233/290

    C++ for Engineers and Scientists, Second Edition 233

    Nested LoopsNested Loops

  • 8/3/2019 CS10 Coursewares

    234/290

    C++ for Engineers and Scientists, Second Edition 234

    Nested loop: a loop contained within anotherloop

    All statements of the inner loop must becompletely contained within the outer loop; no

    overlap allowed Different variables must be used to control each

    loop

    For each single iteration of the outer loop, the

    inner loop runs through all of its iterations

  • 8/3/2019 CS10 Coursewares

    235/290

    Nested Loops (continued)Nested Loops (continued)

  • 8/3/2019 CS10 Coursewares

    236/290

    C++ for Engineers and Scientists, Second Edition 236

    dowhiledowhile LoopsLoops

    l i tt t l

  • 8/3/2019 CS10 Coursewares

    237/290

    C++ for Engineers and Scientists, Second Edition 237

    dowhile loop is a posttest loop Loop continues while the condition is true

    Condition is tested at the end of the loop

    Syntax:

    do

    statement;

    while (expression);

    All statements are executed at least once in aposttest loop

    dowhiledowhile Loops (continued)Loops (continued)

  • 8/3/2019 CS10 Coursewares

    238/290

    C++ for Engineers and Scientists, Second Edition 238

    Figure 5.11The do

    statements

    flow ofcontrol.

    dowhiledowhile Loops: Validity ChecksLoops: Validity Checks

  • 8/3/2019 CS10 Coursewares

    239/290

    C++ for Engineers and Scientists, Second Edition 239

    Useful in filtering u