C++Lang chap4

  • View
    219

  • Download
    0

Embed Size (px)

Text of C++Lang chap4

  • 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