+ All Categories
Home > Documents > C++Lang chap4

C++Lang chap4

Date post: 03-Jun-2018
Category:
Upload: samaan
View: 247 times
Download: 1 times
Share this document with a friend

of 34

Transcript
  • 8/11/2019 C++Lang chap4

    1/34

    CHAPTER 4

    Control Statements in C++

    4.1 CONDITIONAL STATEMENTSMany times in real-life applications, you will usually need to change the sequence of execution

    according to specified conditions. Sometimes you need to use a simple condition like:

    "If it is cold then put your coat on."

    In this statement the resultant action is taken if the condition is evaluated true(the weather is

    cold). The conditions could be multiple, as in the following conversation:

    "Ok then, if I come back early from work, Ill see you tonight;else if it is too late Ill make it tomorrow; else if my brotherarrives tomorrow we can get together on tuesday; else if tuesdayis a holiday then let it be wednesday; else Ill call you to

    arrange for the next meeting!"C++ programming can easily handle such chained or nested conditions as long as you write the

    adequate code. In C++ there are many control structures that are used to handle conditions and the

    resultant decisions. You have already seen how to express conditions using the conditional opera-

    tor (?). In this chapter you are introduced to more powerful tools: the if..else,while..doand for

    constructs.

    4.1.1 General form of the if else statement

    Theifstatement tests a particular condition. Whenever that condition evaluates astrue, an action

    or a set of actions is executed. Otherwise, the action(s) are ignored. The syntactic form of the if

    statement is the following:

    if (expression)statement;

    Theexpressionmust be enclosed within parentheses. If it evaluates to a nonzero value, the

    condition is considered as true and thestatementis executed.

    Theifstatement also allows answer for the kind ofeither orcondition by using anelseclause.

    Then the syntactic form of the if else statement is the following:

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    2/34

    62 Programming in C++ Part I

    if (expression)statement-1;

    elsestatement-2;

    If the expression evaluates to a nonzero value, the condition is considered to be true and

    statement-1 is executed; otherwise, statement-2 is executed. Note that statement-1 is terminated by

    asemicolon.

    The syntax mirrors the syntax we use in everyday language. For example, the sentence, "ifthe light is red, stop, otherwise, go" would be written in C++ as:

    if (light == red)

    stop;else

    go;

    In the program shown as Figure 4.1 a credit card limit is tested for a certain purchase. The

    value of the variable "amount" is received from the keyboard, then tested using the if statement. If

    the condition istrue(i.e. the "amount" is less than or equal to 1000), the message "your charge is

    accepted" is displayed. If the condition isfalse, the program ends with a message that the amount

    exceeds the credit limit.

    /* Credit card program */#include main(){

    int amount;cout > amount;if (amount

  • 8/11/2019 C++Lang chap4

    3/34

    Part I Control Statements in C++ 63

    Solution

    The program is shown in Figure 4.2.

    #include #include /* Include file for sqrt () */main (){double num;cout num ;if (num

  • 8/11/2019 C++Lang chap4

    4/34

    64 Programming in C++ Part I

    { cout

  • 8/11/2019 C++Lang chap4

    5/34

    Part I Control Statements in C++ 65

    #include main (){double x,y;cout x >> y;if (x > y)cout

  • 8/11/2019 C++Lang chap4

    6/34

    66 Programming in C++ Part I

    Ex a m p le 4

    Correct the program shown in Figure 4.7.

    #include main ()double num1,num2,num3;double sum,product;cout num1 >> num2 >> num3;if (num1 < 0)

    {product = num1 * num2 * num3; cout

  • 8/11/2019 C++Lang chap4

    7/34

    Part I Control Statements in C++ 67

    You can include the two results of the condition (TRUE and FALSE) in one construct by using

    the complete if-else structure, which takes the form:

    if (condition)statement1;

    elsestatement2;

    In this form, the body of the condition structure is separated from the rest of the program.

    When the condition is evaluated, one of the two result statements will be executed, then the pro-

    gram would resume its original flow.

    Using blocks makes it possible to use many statements as results for either the TRUE or

    FALSE conditions. Example 5 will make the point more clear.

    Ex a m p le 5

    The credit card program shown in Figure 4.3 is rewritten using the compound statements. The

    same is shown in Figure 4.9.

    /* Credit card program with compound statements */#include main(){float amount;coutamount;

    if (amount

  • 8/11/2019 C++Lang chap4

    8/34

    68 Programming in C++ Part I

    4.1.3 The if else if ladder

    The conditions and their associated statements can be arranged in a construct that takes the form:

    if (condition1)statement1;

    else if (condition2)statement2;

    else if (condition3)statement3;

    ...else

    statementn;The different conditions are evaluated from the top down, and whenever a condition is evalu-

    ated astrue, the corresponding statement(s) are executed and the rest of the construct is skipped.

    This construct is referred to as the if-else-if ladder. This is explained in Example 6.

    Ex a m p le 6

    Suppose that you want to test the ASCII code of a received character to check if it is an alphabetic

    character. If it is so, you would like to check if it is lower case or upper case. Knowing that the

    ASCII codes for the upper case letters are in the range 65-90, and those for lower case letters are in

    the range 97-122. Program shown in Figure 4.10 establishes the logic:

    /* Program to demonstrate if-else-if ladder */#include #include main(){

    char a;cout a;if (a > 64 && a < 91) cout 96 && a < 123) cout

  • 8/11/2019 C++Lang chap4

    9/34

    Part I Control Statements in C++ 69

    charbut not of type double. Thus, instead of using the if-else-if ladder, the switch structure is

    ready to handle multiple choices, such as menu options. The general form of the switch structure

    is:

    Switch(variable){

    case constant1;statement(s):break;

    case constant2:statement(s);break;

    case constant3:statement(s);break;

    ---default:

    statement(s);}

    The switch structure starts with the keywordswitchfollowed by one block which contains the

    different cases. Each case handles the statements corresponding to an option (a satisfied condition)

    and ends with the break statement which transfers the control out of the switch structure to the

    original program. The variable within the parentheses following the switch keyword is used to test

    the conditions and is referred to as thecontrol variable. If it is evaluated as "constant1," the "case

    constant1:" is executed. If evaluated as

    "constant2," the "case constant2:" is executed, and so forth. If the value of the variable does not

    correspond to any case, the default case is executed. The control variable of the switch could be of

    the type int, long, or char. Other types are not allowed. Example 7 demonstrates the use of the

    switch statement.

    Ex a m p le 7

    The menu option in Figure 4.11 uses the switch statement.

    /* Program Demonstrating switch construct */#include

    #include main(){

    char choice;char *a,*b,*c,*d,*e,*f,*g,*h;a=" MAIN MENU";

    (Contd...)

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    10/34

    70 Programming in C++ Part I

    b="-------------------------------------";c="1- WordPerfect.";d="2- Lotus 1-2-3.";e="3- dBASE IV.";f="4- AutoCAD.";g="5- Exit to DOS.";h="Press the required number:";cout

  • 8/11/2019 C++Lang chap4

    11/34

    Part I Control Statements in C++ 71

    Figure 4.12

    Menu selection

    using switch

    construct

    MAIN MENU

    -------------------------------------

    1- WordPerfect.

    2- Lotus 1-2-3.

    3- dBASE IV.

    4- AutoCAD.

    5- Exit to DOS.

    Press the required number:

    4

    AutoCAD is chosen.

    This is the end of the SWITCH.

    Back to the program.

    Figure 4.13

    Selecting

    wrong choice

    in menu

    The switch construct can be nested, if needed, using the block separators ({ }). In this case, you

    can include another switch inside any case.The function exit is used to terminate the program execution. It takes the form :

    exit(status);

    For normal termination, the argument value can be zero (0). In case of errors any other number

    may be used.

    MAIN MENU

    -------------------------------------

    1- WordPerfect.

    2- Lotus 1-2-3.

    3- dBASE IV.

    4- AutoCAD.

    5- Exit to DOS.

    Press the required number:

    6

    Sorry, wrong key.

    This is the end of the SWITCH.

    Back to the program.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    12/34

    72 Programming in C++ Part I

    4.2.1 Comparison of nested ifstatements and the switchstatement

    Ex a m p le 8

    Give the output of the segment of the program containing switch statement and shown as Figure

    4.14.

    You can use a nested if statement, which is more general than the switchstatement, to imple-

    ment any multiple-alternative decision. The switch as described above is more readable in many

    programs and should be used wheneverpractical.

    #includemain()

    { char next_ch;cin >> next_ch;

    /* Start of the switch block */switch(next_ch){case A:case a:cout

  • 8/11/2019 C++Lang chap4

    13/34

    Part I Control Statements in C++ 73

    4.3 THE CONDITIONAL OPERATOR ? AS ALTERNATIVE TO IF

    The conditional operator?consists of two operators used on three different expressions, and thus

    it has the distinction of being the only ternary operator in C++. The ternary operators work on

    three variables, as opposed to the more commonly used binary operators, such as plus (+), which

    operate on two expressions, and the unary operators, such as (!) which operate on one. The condi-

    tional operator has the syntax:

    condition ? expression1 : expression2;

    The conditional operator consists of both the question mark and the colon.Conditionis a log-

    ical expression that evaluates to eithertrueorfalse, whileexpression1andexpression2are either

    values or expressions that evaluate to values.

    First the condition is evaluated. If it is true the entire conditional expression takes on the value

    of expression1. If it is false, the conditional expression takes on the value of expression2. Note that

    the entire conditional expression the three expressions and two operators takes on a value and

    can therefore be used in an assignment statement.

    Ex a m p le 9

    Explain the following conditional statement:

    max = (num1 > num2) ? num1 : num2;

    Solution

    The purpose of this statement is to assign to the variable max the value either num1 or num2,

    whichever is larger. First the condition (num1 > num2) is evaluated. If it is true, the entire condi-tional expression takes on the value of num1; this value is then assigned to max.

    If (num1 > num2) is false, the conditional expression takes on the value of num2, and this

    value is assigned to max. This expression is shown in Figure 4.15.

    Figure 4.15

    The condi-

    tional operator

    This expression is equivalent to the if-else statement:

    max = num1: num2;?( num1 > num2 )

    if true

    if falsequestion

    markoperator

    colonoperator

    One or the other

    expression isassigned to max

    Expression takes

    on value of num 1

    on value of num 2

    Expression takes

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    14/34

    74 Programming in C++ Part I

    if (num1 < num2)max = num2;

    elsemax = num1;

    You will notice that the conditional statement is more compact than the if-else since the entire

    statement takes on a value. The two separate statements are not needed. The conditional operator

    can be used more elegantly as given in Example 10.

    Exa m pl e 10

    Explain the following conditional statement:

    abs = (num < 0) ? -num : num;Solution

    The statement evaluates to the absolute value of num, which is simply num if num is greater than

    zero, but num if num is less than zero. Thus it always gives the absolute value of num.

    4.4 SIMPLE CONTROL STATEMENTS

    Control statements define the way or flow in which the execution of a program should take place

    to achieve the required result. Control statements also implement decisions and repetitions in pro-

    grams.

    Four types of control structures are supported by C++. They are:

    (a) Unconditional control (goto)

    (b) Bi-directional control (if..else)

    (c) Multidirectional conditional control (switch)

    (d) Loop control

    (i) do..while

    (ii) while

    (iii) for..

    The bi-directional control (if..else) structure and switchstructure are explained in Sections

    3.1.1 and 3.2 respectively. The other control structures are explained in the following sections.

    4.4.1 Unconditional Control (goto)

    In some situations, the flow of control may be transferred to another part of the program without

    testing for any condition. In such cases,gotois used.gotoshould be followed by a label name andthe C++ program should have only one statement having that label qualifier in the block, in which

    gotois used.

    The syntax for goto is:

    label: statement;

    The label is a valid C++ identifier followed by a colon. You can precede any statement by a

    label in the form:

    label: statement;

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    15/34

    Part I Control Statements in C++ 75

    You can, for example, make a loop in the Example 6 to repeat the program execution infi-

    nitely. This is done by adding a goto statement and a label, as in Example 11. In this example we

    use the label "START" at the very beginning. The last statement in the program is:

    goto START;

    Exa m pl e 11

    Program in Figure 4.16 demonstrates if-else-if ladder,

    /* Program to demonstrate if-else-if ladder */#include #include main(){

    char a;START: cout a;if (a == 0) exit(0);else if (a > 64 && a < 91) cout 96 && a < 123) cout

  • 8/11/2019 C++Lang chap4

    16/34

    76 Programming in C++ Part I

    Figure 4.17

    Concept of

    looping

    In step 5 of Figure 4.17, the current value of A is compared with 21. If the current value of A is

    less than 21, steps 3 and 4 are repeated. As soon as the current value of A is not less than 21, the

    path corresponding to "NO" is followed and the repetition process stops.Te rm s Use d in Loo p ing

    Initialization It is the preparation required before entering a loop. In Figure 4.17, step 2 initializesthe value of A as 1.

    Incrementation. It is the numerical value added to the variable each time one goes round theloop. Step 4 in Figure 4.17 shows the increment of A by 1.

    The Loop Variable. It is an active variable in a loop. In Figure 4.17, A is the active variable.

    Loop Exit Test. There must be some method of leaving the loop after it has circled the requisitenumber of times. In Figure 4.17, step 5 is the decision diamond, where the value of A is comparedwith 21. As soon as the condition is satisfied, control comes out of the loop and the process stops.

    Exa m pl e 12

    Draw a flowchart for calculating the salary of 100 workers in a factory.

    Solution

    Figure 4.18 represents the flowchart. In this figure, step 2 is for initialization of the value of

    COUNT where COUNT is an active variable. Step 7 is the incrementation. Step 3 is for the EXIT

    test. Steps 4 to 6 are the repetitive steps in the loop to input the NAME, WAGE and HOURS, and

    A < 21

    YES

    ?

    IS NO

    BEGIN

    (A + 1)A

    END

    A = 1

    PRINT A

    STEP 1

    STEP 2

    STEP 3

    STEP 4

    STEP 5

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    17/34

    Part I Control Statements in C++ 77

    Figure 4.18

    Flowchart for

    calculating sal-

    ary of 100

    workers

    then calculate the value of PAY in step 5 and print the name and pay in step 6. In step 7, the value

    of COUNT is increased by 1 and the current value of COUNT is compared with 100 in step 3. If it

    is more than 100, the process is halted.

    Exa m pl e 13

    How many times the value of K will be read in the flowcharts shown in Figures 3.19 and 3.20?

    Solution

    The value of K will be read 15 times in both cases.

    3.5.2 Counting

    Counting is an essential technique used in the problem solving process. It is mainly for repeating a

    procedure for a certain number of times or to count the occurrences of specific events or to gener-

    ate a sequence of numbers for computational use. Since a computer cannot count by itself, the user

    has to include the necessary instruction in the program to do so.

    COUNT > 100

    ?

    IS

    BEGIN

    WAGE x HOURSPAY

    COUNT = 1

    STEP 1

    STEP 2

    END

    HOURSNAME, WAGE,

    INPUT

    PRINT NAME, PAY

    COUNT + 1COUNT

    STEP 3

    STEP 4

    STEP 5

    STEP 6

    STEP 7

    NO

    YES

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    18/34

    78 Programming in C++ Part I

    Figure 4.19 Figure 4.20

    Flowchart Flowchart

    for counting for counting

    records records

    The counting process is illustrated in the flowchart shown in Figure 4.21. Here I is a counter

    which is initialized to a value zero in step 2. In step 3, a NAME is read and stored in the memory

    of the computer. The value of the counter is incremented by 1 in step 4. In step 5, the NAME is

    printed from the memory of the computer. In step 6, a check is made on the value of I. If the

    current value of I is less than 5, the cycle is repeated from steps 3 to 5. If the value of I is equal to

    or more than 5, the process of reading and printing NAME stops. Using this type of flowchart we

    can read and print the NAME five times.

    C ounting for C ontrol ling a Loo p

    Sometimes, it is essential to repeat a process for a specific number of times. In such a case, two

    standard techniques used are as follows:Technique 1 In this technique, we use the following six steps.

    (1) Initialize a counter to 0, i.e. COUNT = 0. Input value of N where N stands for the number

    of times a loop is to be repeated.

    (2) Increase the counter by 1, i.e. COUNT = COUNT + 1

    (3) Test the value of counter and compare the current value with N. If the current value of the

    COUNT is greater than N, then branch off to (6), otherwise continue.

    BEGIN

    I = 0

    I

    READ

    I = 15

    NO

    ?

    IS

    END

    YES

    RECORD

    I + 1

    BEGIN

    I = 0

    I

    READ

    I > 15

    NO

    ?

    IS

    END

    YES

    I + 1

    RECORD

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    19/34

    Part I Control Statements in C++ 79

    Figure 4.21

    Counting pro-

    cess

    Figure 4.22 Figure 4.23

    Flowchart Flowchart

    for printing for printing

    numbers numbers

    (4) Carry out the sets of instructions (procedure).

    BEGIN

    I

    I < 5

    NO

    ?

    IS

    END

    YES

    (I + 1)

    I = 0

    READ NAME

    PRINT NAME

    STEP 1

    STEP 2

    STEP 3

    STEP 4

    STEP 5

    STEP 6

    STEP 7

    BEGIN

    END

    INPUT N

    IS

    COUNT > N

    ?

    SET OF

    INSTRUCTIONS

    COUNT = 0

    COUNT COUNT + 1

    YES

    STEP 1

    STEP 2

    STEP 3

    STEP 4

    STEP 6

    STEP 5

    NO

    BEGIN

    END

    INPUT N

    IS

    COUNT < N

    ?

    SET OF

    INSTRUCTIONS

    COUNT = 0

    COUNT COUNT + 1

    NO

    YES

    STEP 1

    STEP 2

    STEP 3

    STEPS 4 & 5

    STEP 6

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    20/34

    80 Programming in C++ Part I

    (5) Go back to (2).

    (6) End the loop and continue further programming. These six steps are shown in Figure 4.22.

    Te c hnique 2

    (1) In this method, the counter is first initialized to zero and the value of N is inputted.

    (2) Carry out the sets of instructions of the program.

    (3) Increase the counter by 1.

    (4) Test the counter. If COUNT < N then go to (2).

    (5) else END

    The above mentioned five steps are represented pictorially by the flowchart shown in Figure 4.23.

    Exa m pl e 14 Which numbers will be printed by the flowcharts shown in Figures 3.24 and 3.25 respectively?

    Figure 4.24 Figure 4.25

    Flowchart Flowchart

    for print- for print-

    ing num- ing num-

    bers bers

    In Figure 4.24, the value of I is initialized to zero in step 2. In step 3, the value is incremented

    by 1, i.e. it is 1. In step 4, I is printed. In step 5, the current value of I is compared with 5. Since the

    current value of I is 1 and 1 is not greater than or equal to 5, the control is transferred to step 3.

    Steps 3 and 4 are repeated till the current value of I is 5. Thus, the values of I that are printed

    would be 1, 2, 3, 4, 5.

    BEGIN

    I = 0

    I

    PRINT I

    I > 5

    YES

    ?

    IS

    END

    NO

    I + 1

    STEP 1

    STEP 2

    STEP 3

    STEP 4

    STEP 5

    STEP 6

    BEGIN

    I = 1

    I

    PRINT I

    I < 5

    NO

    ?

    IS

    END

    YES

    I + 1

    STEP 1

    STEP 2

    STEP 3

    STEP 4

    STEP 5

    STEP 6

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    21/34

    Part I Control Statements in C++ 81

    In Figure 4.25, the value of I is initialized to 1 in step 2. The number 1 is printed in step 3. In

    step 4, the value of I is increased by 1. So the current value of I is 2. In step 5, 2 is compared with

    5. Since 2 is less than 5, the control is transferred to step 3 and the number 2 is printed. This cycle

    repeats and numbers 3 and 4 are printed. When the current value of I reaches 5, the control is

    transferred from step 5 to 6. Thus the numbers printed are 1, 2, 3 and 4.

    4.5.3 The While Statement

    The repetition of a group of program statements called a loop usingwhileandforstatements give

    computers the magnificent ability to process data. Just as the ability to make decisions is an

    important programming tool, so is the ability to specify repetitions of a group of operation. When

    we do not know the exact number of loop repetitions before the loop execution begins, then we use

    while..do loop control statement. For example, we may wish to continue writing cheques as longas our bank balance is above Rs. 250.00.

    Figure 4.26 shows the flow of control for a simple while statement. So long as x is less than y,

    the program continues to execute the while loop. With each pass through the loop, however, x is

    incremented by one. When it is no longer less than y, control flows to the next statement.

    Because the incrementing operation occurs so frequently, the C++ language has a special

    increment operator called ++. The while statement shown in Figure 4.26 would normally be writ-

    ten as

    Figure 4.26

    Flow control of

    a while statement

    while (x < y)

    x++;Exa m pl e 15

    The program in Figure 4.27 displays the string "Hello World" five times using the while loop.

    x < y

    x = x + 1

    False

    Truewhile ( x < y )

    x = x + 1;

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    22/34

    82 Programming in C++ Part I

    /* Demonstration of while loop */#include main(){

    int c=0;while (c

  • 8/11/2019 C++Lang chap4

    23/34

    Part I Control Statements in C++ 83

    Exa m pl e 17

    factorial = factorial * number ;

    This statement is equivalent to two statements:

    factorial = factorial * number

    number = number 1;

    In Figure 4.29, thewhileloop is used to calculate the factorial of a number. In this program, the

    number is received from the keyboard using thecinfunction and is assigned to the variable "num-

    ber". The variable "factorial" isdeclared as long intto hold the expected large number and is ini-

    tialized with the value "1". The final value of the factorial is reached through theiterative process:

    /* Calculation of factorial */#include

    main()

    {

    int number;

    long int factorial=1;

    cout number;

    while (number > 1)

    factorial = factorial * number ;

    cout

  • 8/11/2019 C++Lang chap4

    24/34

    84 Programming in C++ Part I

    /* Demonstration of do while statement */#include main(){

    int c=0;do { cout

  • 8/11/2019 C++Lang chap4

    25/34

    Part I Control Statements in C++ 85

    Figure 4.32

    Structure of

    theforloop

    The Initia lize Exp ression

    The initialize expressionnumber =0, initializes thenumbervariable. The initialize expression is

    always executed as soon as the loop is entered. In this case we initializenumberto 0.

    Expression Name Purpose

    (1) number = 0 Initialize expression Initializes the loop variable(2) number < 0 Test expression Tests the loop variable(3) number++ Increment expression Increments the loop variable

    The Te st Exp re ssio n

    The second expression,number

  • 8/11/2019 C++Lang chap4

    26/34

    86 Programming in C++ Part I

    To do this, it uses the increment operator (++), described earlier. Note that the loop variable in a

    forloop does not have to be increased by 1 each time through the loop. It can also be decreased by

    1, or changed by some other number, using an expression such as :

    number = number + 3;

    In other words, practically any expression can be used for the increment expression.

    The Bod y o f the Loo p

    Following the keywordforand the loop expression is the body of the loop: this is, the statement

    (or statements) that will be executed each time round the loop. In this example, there is only one

    statement:

    cout

  • 8/11/2019 C++Lang chap4

    27/34

    Part I Control Statements in C++ 87

    then the test condition is examined. If the test expression is false to begin with, the body of the

    loop will not be executed at all. If the condition is true, the body of the loop is executed and, fol-

    lowing that, the increment expression is executed. That is why the first number printed by the

    program is 0 and not 1. Printing takes place before the number is incremented by the (++)

    operator. Finally the loop recycles and the test expression is queried again. This will continue until

    the test expression becomes false number becomes 10 at which time the loop will end.

    I mp orta nce o f the fo r sta te m e nt

    C++ permits an unusual degree of flexibility in the writing of the forloop. For example, if sepa-

    rated by commas, more than one expression can be used for the initialize expression and for the

    increment expression, so that several variables can be initialized or incremented at once.

    Exa m pl e 20

    The program shown in Figure 4.34 prints the numbers 0 to 9 and the running total as shown in

    Figure 4.35.

    #includemain(){int number,total=0;for (number = 0; number < 10; number++){total += number;cout

  • 8/11/2019 C++Lang chap4

    28/34

    88 Programming in C++ Part I

    an if-then or while..loop is placed within the beginning and end of another loop, it is said to be

    nested. For example, the program to calculate the factorial of a number as given in Example 17 can

    be modified as written in Example 21.

    Ex a m p le 2 1

    The factorial program of Example 17 is included into an infinite forloop which ends only if you

    enter the number 0. In this case, theforloop is called the outer loop and thedo-whileloop is called

    the inner loop. The program is shown in Figure 3.36.

    /* Factorial calculation using a nested loop */#include #include main(){

    int number, counter; long int factorial;for (;;) { factorial=1; coutnumber; if (number==0) exit(0); counter=number; do {

    factorial = factorial * counter-- ; } while (counter > 1); cout

  • 8/11/2019 C++Lang chap4

    29/34

    Part I Control Statements in C++ 89

    /* Demonstration of nested forloops */#include main(){

    int x,y;for (x=1; x

  • 8/11/2019 C++Lang chap4

    30/34

    90 Programming in C++ Part I

    Exa m pl e 24

    Program shown in Figure 4.41 prints a multiplication table using two forloops. The output is

    shown in Figure 4.42.

    /* Generation of Multiplication Table */#include main (){

    int cols, rows, product;for(rows = 1; rows < 4; rows++) /* outer loop */{

    for (cols = 1; cols < 4; cols++) /* inner loop */cout

  • 8/11/2019 C++Lang chap4

    31/34

    Part I Control Statements in C++ 91

    /* Breaks out of the while statement when i > 5 */if (i > 5)break;}cout 0; j++, k--);

    In this example, both j and k are initialized before the loop is entered. After each iteration, j is

    incremented and k is decremented. It is equivalent to the followingwhileloop.

    j = 0;k = 100;while (k - j

  • 8/11/2019 C++Lang chap4

    32/34

    92 Programming in C++ Part I

    TEST PAPER

    Time: 3 Hrs

    Max Marks: 100

    Answer the following questions.

    1. In a simpleifstatement with no else, what happens if the condition following theifis

    false?

    (a) The program searches for the lastelsein the program.

    (b) Nothing

    (c) Control falls through to the statement following theif.

    (d) The body of theifstatement is executed.

    Ans[both (b) and (c) are correct]

    2. The main difference in operation between anifstatement and awhilestatement is:

    (a) The conditional expression following the keyword is evaluated differently.

    (b) Thewhileloop body is always executed, theifloop body only if the condition is

    true.

    (c) The body of thewhilestatement may be executed many times, the body of theif

    statement only once.

    (d) The conditional expression is evaluated before thewhileloop body is executed

    but after theifloop body.

    Ans(c)

    3. The advantage of aswitchstatement over an else-if construction is:

    (a) A default condition can be used in theswitch.

    (b) Theswitchis easier to understand.

    (c) Several different statements can be executed for each case in a switch.

    (d) Several different conditions can cause one set of statements to be executed in a

    switch.

    Ans(b)

    4. State all the loop control structures supported by C++ and compare them.

    5. State the use of the following giving an example of each.

    (a) break

    (b) continue

    6. Write an algorithm and use it to write a program in C++ to compute a sales persons

    commission based on the following table:

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    33/34

    Part I Control Statements in C++ 93

    Amount Sales Commission (% of sales)

    Under Rs. 500 2%

    Rs. 500 or more 5%

    but under Rs. 5000

    Rs. 5000 and above 10%

    7. Write a program in C++ based on the following algorithm.

    BEGIN

    Input mortgage amount

    IFamount < 15,000

    THENdown payment = 3% of amount

    ELSE

    payment 1 = 3% of 10,000

    payment 2 = 5% of (amount - 10,000)

    down payment = payment 1 + payment 2

    END IF

    print down payment

    8. Sales mans commission is calculated using the following Pseudocode. Use this for writ-

    ing a program in C++.

    Input sales

    IFsales < 1500THEN

    Commission = 2% of sales.

    ELSE

    Commission = 5% of sales.

    END IF

    Print Commission

    9. A company gives commission to its sales personal on the basis of the sales of two of its

    products X and Y. The commission percentage is the same for both products and is

    applicable only when the sales value is equal to or more than Rs 5000. The commission

    percentage rates are 2% for sales >= 5000 and < Rs. 7000 and 5% for sales >= Rs. 7000.

    Commission is calculated as the product of sales value and commission percentage for

    each product. In addition to commission, there is an additional sales Bonus disbursed,when the cumulative sales value of both the products exceed Rs 20000. This bonus is

    calculated as 1% of the total sales. Write a program in C++ to accept from any salesman,

    the sales value of each of the products X and Y and display the individual commission

    on each product, the total commission and additional bonus as applicable.

    10. Study the following conditions. Write and test a program in C++ to satisfy these condi-

    tions.

    bpbonline all rights reserved

  • 8/11/2019 C++Lang chap4

    34/34

    94 Programming in C++ Part I

    (a) If the product code equals A, and the customer type equals 1 and if the order

    amount is less than or equal to Rs 1500, then allow a discount of 4.8%.

    (b) If the product code equals A and the customer type equals 2 and if the order

    amount is less than or equal to Rs 1500, then allow a discount of 8.9%.

    (c) If the product code equals A, and the customer type equals 1 and if the order

    amount is greater than Rs. 1500, then allow a discount of 8%.

    (d) If the product code equals A, and the customer type equals to 2 and if the order

    amount is greater than Rs 1500, then allow a discount of 10%.

    (e) Give a flat discount of 3% on product code B regardless of the customer type

    and the order amount.


Recommended