chapter 05 control

Upload: satkm87

Post on 03-Jun-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Chapter 05 Control

    1/23

    Control Statements5.1. INTRODUCTION

    The term flow of control refers to the order in which a programs statementsare executed. Every programming language supports three control flow structuresnamely :

    1. Sequential control structure2. Selective control structure. !terative control structure

    5.1.1. Sequential Control Structure

    The normal flow of control of all programs is sequential. !n sequentialstructure" a sequence of programs statements are executed one after another inthe order in which they are placed. #oth selection and repetition statementsallows allow the programmer to alter the normal sequential flow of control.

    Sequential programming can also $e called linear programming. Thesequential programs are non%modular in nature. That is" reusa$ility of code is notpossi$le. Thus" they are difficult to maintain and understand. Examples ofsequence control structure statements are" the program will have statements thatare placed sequentially and there is no decision involved in the process. &lso" theprogram does not require a specific tas' to $e repeated over and over again.

    5.1.2. Selective Control Structure (or) Decision Control Structure

    The selective structure allows the usual sequential order of execution to $emodified. !t consists of a test for a condition followed $y alternative paths that theprogram can follow. The program selects one of the alternative paths dependingupon the result of the test for condition. Examples of selective control structuresstatements are :

    1. Simple if statement2. if . . . else statement

    . (ested if . . . else statement). else if ladder*. switch . . . case . . .default statement

  • 8/12/2019 Chapter 05 Control

    2/23

    5.2 Control Statements

    5.1.3. Iterative Control Structure (or) oo! Control Structure

    The iterative structure provides the a$ility to go $ac' and repeat a set ofstatements. !terative structure is otherwise referred to as repetitive structure.

    The + language has the a$ility to repeat the same calculation or sequence ofinstructions over and over again" each time using different data. The iterativestructure consists of an entry point that includes initiali,ation of varia$le" a loopcontinuation condition" a loop $ody and an exit point. Examples of iterativecontrol structure statements are :

    1. while statement2. do . . . while statement. for statement

    5.2. i" ST#T$%$NTS

    + allows decisions to $e made $y evaluating a given expression as true orfalse. Such an expression involves the relational and logical operators. -ependingon the outcome of the decision" program execution proceeds in one direction oranother. The + statement that ena$les these tests to $e made is called the ifstatements.

    The if statements may $e implemented in different forms depending on thecomplexity of conditions to $e tested. They are :

    1. Simple if statement2. if . . . else statement

    . (ested if . . . else statement). else if ladder

    5.2.1. Sim!le i" Statement

    The simple if statement is used to specify conditional execution of programstatement or a group of statements enclosed in $races. The syntax is :

    if (test condition){

    statement-block ; } statement-x ;

  • 8/12/2019 Chapter 05 Control

    3/23

  • 8/12/2019 Chapter 05 Control

    4/23

    5.4 Control Statements

    or equal to $ * **

    Truealse

    Two or more conditions may $e com$ined in an if statement using a logical&(- operator 6778 or a logical 9 operator 6;;8. !t can compare any num$er ofvaria$les in a single if statement. Ta$le $elow shows the various expressions thatare used as conditions inside an if statement :

    ConditionalExpression

    MeaningFor

    e.g.,al!eof a

    Fore.g.,

    al!e of

    b

    Fore.g.,

    al!e of c

    "es!lt

    66a5$8 77 6$5c88a is greater than

    $ &(- $ isgreater than c

    < 2< 1< True< 1< 2< alse

    1< < 2< alse1< 2< < alse

    66a5$8 ;; 6$5c8a is greater than$ 9 $ is greater

    than c

    < 2< 1< True< 1< 2< True

    1< < 2< True1< 2< < alse

    +onsider the pro$lem for finding the tic'et fare for adult and children. Thepro$lem involves decision" that is" the tas's include :

    &ssuming that the tic'et fare as 1

  • 8/12/2019 Chapter 05 Control

    5/23

    Control Statements 5 .5

    etc+() 09

    RUN 1 4

    $nter t+e a e 4 25

    T+e tic8et "are is Rs. 1

    RUN 2 4

    $nter t+e a e 4 1

    T+e tic8et "are is Rs. 5

    Note 4 There is only one statement in the if $loc'" the $races are optional.#ut if there is more than one statement you must use the $races.

    5.2.2. i" . . . else Statement

    Sometimes" we can execute one group of statements if the condition is trueand another group of statements if the condition is false" in such a situation" theif . . . else statement can $e used.

    The if . . . else statement is an extension of simple if statement. The syntaxis :

    if (test condition){

    tr!e-block-statement(s) ; }else{

    false-block-statement(s) ; } statement-x ;

    !f the test condition is true" then the true%$loc'%statement6s8 are executed. !fthe test condition is false" then the false%$loc'%statement6s8 are executed. !neither case" either true%$loc'%statement6s8 or false%$loc'%statement6s8 will $eexecuted" not $oth.

  • 8/12/2019 Chapter 05 Control

    6/23

    test

    cond

    5.6 Control Statements

    The figure $elow shows the flowchart of simple if statement :

    Entry

    True alse

    To understand this programming construct" let us consider an example ofchec'ing whether the person is eligi$le to vote or not $y getting the age of theperson. The tas' include :

    =etting the input 6age8 from the user. ?a'ing the decision if the age is greater than or equal to 1@" then print

    the person is eligi$le to vote. Else print the person is not eligi$le to vote.

    The following program demonstrates the a$ove pro$lem :

    &' Demonstration o" i" . . . else statement '& inclu e *st io.+, inclu e *conio.+,

    voi main()-

    int a e 0clrscr() 0!rint"( $nter t+e a e 4 ) 0scan"( / 6a e) 0i"(a e , 1:)

    !rint"( 7nT+e !erson is eli i;le to vote. ) 0else

    false%$loc'%statement6s8

    statement%x

    true%$loc'%statement6s8

  • 8/12/2019 Chapter 05 Control

    7/23

    Control Statements 5 .7

    !rint"( 7nT+e !erson is not eli i;le to vote. ) 0etc+() 0

    9

    RUN 1 4

    $nter t+e a e 4 25

    T+e !erson is eli i;le to vote.

    RUN 2 4

    $nter t+e a e 4 1asse in secon class ) 0else i"(mar8 , = )

    !rint"( 7n>asse in t+ir class ) 0else

    !rint"( 7n?aile in t+e e@am. ) 0etc+() 0

    9

    RUN 1 4

    $nter t+e mar8 score 4 asse in "irst class

    RUN 2 4

    $nter t+e mar8 score 4 35

    ?aile in t+e e@am.

    5.3. sAitc+ ST#T$%$NT

    The control statement which allows us to ma'e a decision from the num$er ofchoices is called a switch" or more correctly a switch . . . case . . . default" sincethese three 'eywords go together to ma'e up the control statement.

  • 8/12/2019 Chapter 05 Control

    13/23

    Control Statements 5 .13

    The switch statement tests the value of a given varia$le 6or expression8against a list of case values and when a match is found" a $loc' of statementsassociated with the case is executed. The syntax is :

    s&itc' (expression){

    case al!e-# statement-# ;break ;

    case al!e-$

    statement-$ ;break ;. . .. . .. . .defa!lt

    defa!lt-statement ; } statement-x ;

    /here the expression is an integer expression or characters. value%1" value%2are constants or constant expression 6valua$le to an integral constant8 and are'nown as case la$els. Each of these values should $e should $e unique with aswitch statement. statement%1" statement%2 are statement lists and may containone or more statements. There is no need to put $races around these $loc's. The'eyword case is followed $y an integer or a character constant. Each constant ineach case must $e different from all others and the case la$els end with asemicolon 6:8.

    /hen the switch is executed" the value is computed for expression" thelist of possi$le constant expression values determined from all case statements issearched for a match. !f a match is found" execution continues after the matchingcase statement and continues until a $rea' statement is encountered or the endof statement is reached.

    The $rea' statement at the end of each $loc' signals the end of a particularcase and causes an exit from the switch statement" transferring the control to thestatement%x following the switch. The default is an optional case. !f a match is notfound and the default statement prefix is found within switch" execution continuesat this point. 9therwise" switch is s'ipped entirely and the control goes to thestatement%x.

  • 8/12/2019 Chapter 05 Control

    14/23

    switch

    expr

    5.14 Control Statements

    Note 4 &t the end of every case" there should $e a $rea' statement.9therwise" it will result in causing the program execution to continue into the nextcase whenever case gets executed.

    The figure $elow shows the flowchart of switch statement :

    Entry

    Expression value 1

    Expression value 2

    . . .

    . . .-efault 6no match8 . . .

    statement%1

    statement%2

    default statement

    statement%x

  • 8/12/2019 Chapter 05 Control

    15/23

    Control Statements 5 .15

    +onsider the following program to read a num$er from 1 to 1< and print thecorresponding num$er in words :

    &' Demonstration o" sAitc+ ... case ... e"ault statement '& inclu e *st io.+, inclu e *conio.+,

    voi main()-

    int num 0

    clrscr() 0!rint"( $nter a num;er *1 to 1 , 4 ) 0scan"( / 6num) 0sAitc+(num)-

    case 1 4!rint"( 7nON$ ) 0;rea8 0

    case 2 4!rint"( 7nTBO ) 0;rea8 0

    case 3 4!rint"( 7nT R$$ ) 0;rea8 0

    case = 4!rint"( 7n?OUR ) 0;rea8 0

    case 5 4!rint"( 7n?I $ ) 0;rea8 0

    case < 4!rint"( 7nSIE ) 0;rea8 0

    case F 4!rint"( 7nS$ $N ) 0;rea8 0

    case : 4!rint"( 7n$IG T ) 0;rea8 0

    case H 4!rint"( 7nNIN$ ) 0;rea8 0

    case 1 4!rint"( 7nT$N ) 0

  • 8/12/2019 Chapter 05 Control

    16/23

    5.16 Control Statements

    ;rea8 0e"ault 4

    !rint"( 7nInvali In!ut. ) 09

    etc+() 09RUN 1 4

    $nter a num;er *1 to 1 , 4 5

    ?I $

    RUN 2 4

    $nter a num;er *1 to 1 , 4 12

    Invali In!ut.

    5.=. oto ST#T$%$NT

    The goto statement is used to alter the normal sequence of programexecution $y unconditionally transferring control to some part of the program. Thesyntax is :

    goto label

    /here la$el is an identifier used to la$el the target statement to which thecontrol would $e transferred. +ontrol may $e transferred to any other statementwithin the current function. The target function must $e la$eled followed $y acolon. The syntax is :

    label statement ;

    +onsider the following program for finding winning team in a cric'et match :

    &' Demonstration o" oto statement '& inclu e *st io.+, inclu e *conio.+,

    voi main()-

    int in / !a8 0clrscr() 0!rint"( $nter t+e In ia s score 4 ) 0scan"( / 6in ) 0

  • 8/12/2019 Chapter 05 Control

    17/23

  • 8/12/2019 Chapter 05 Control

    18/23

    testcond

    5.18 Control Statements

    control is transferred out of the loop. 9n exit" the program continues with thestatement%x which is immediately after the $ody of the loop.

    Note 4 The test condition specified in the while loop should eventually$ecome false at one point of the program" otherwise the loop will $ecome aninfinite loop.

    The figure $elow shows the flowchart of while statement :

    Entry

    alse

    True

    $ody of the loop

    statement%x

  • 8/12/2019 Chapter 05 Control

    19/23

    Control Statements 5 .19

    +onsider the following program to find the sum of first n num$ers :

    &' Demonstration o" A+ile statement '& inclu e *st io.+, inclu e *conio.+,

    voi main()-

    int n/ count 1/ sum 0clrscr() 0!rint"( $nter t+e value "or n 4 ) 0scan"( / 6n) 0A+ile(count * n)-

    sum sum J count 0count count J 1 0

    9!rint"( 7nT+e sum o" "irst num;ers is 4 / n/ sum) 0

    etc+() 09

    RUN 1 4

    $nter t+e value "or n 4 5

    T+e sum o" "irst 5 num;ers is 4 15

    5.

  • 8/12/2019 Chapter 05 Control

    20/23

    testcond

    5.20 Control Statements

    do{

    bod* of t'e loop ; } &'ile(test condition) ; statement-x ;

    /here the $ody of the loop may have one or more statements. 9n reachingthe do statement" the program proceeds to evaluate the $ody of the loop first. &tthe end of the loop" the test condition in the while statement is evaluated. !f thecondition is true" then the program continues to evaluate the $ody of the looponce again. This process continues as long as the condition is true. /hen thecondition $ecomes false" the loop will $e terminated and the control goes to the

    statement%x that appears immediately after the while statement.

    The figure $elow shows the flowchart of do . . . while statement :

    Entry

    True

    alse

    statement%x

    $ody of the loop

  • 8/12/2019 Chapter 05 Control

    21/23

    Control Statements 5 .21

    +onsider the following program to find the sum of two num$ers for n num$erof times :

    &' Demonstration o" o . . . A+ile statement '& inclu e *st io.+, inclu e *conio.+,

    voi main()-

    int num1/ num2 0

    c+ar c+oice 0clrscr() 0o

    -!rint"( 7n$nter t+e "irst num;er 4 ) 0scan"( / 6num1) 0!rint"( 7n$nter t+e secon num;er 4 ) 0scan"( / 6num2) 0!rint"( 7n J / num1/ num2/ num1 J num2) 0""lus+(st in) 0!rint"( 7n7nDo Kou Aant to continue (L&N) 4 ) 0scan"( c / 6c+oice) 0

    9 A+ile((c+oice L ) MM (c+oice K )) 0etc+() 0

    9

    RUN 1 4

    $nter t+e "irst num;er 4 2

    $nter t+e secon num;er 4 5

    2 J 5 F

    Do Kou Aant to continue (L&N) 4 K

    $nter t+e "irst num;er 4 1

    $nter t+e secon num;er 4 2

    1 J 2 3

    Do Kou Aant to continue (L&N) 4 n

  • 8/12/2019 Chapter 05 Control

    22/23

    5.22 Control Statements

    5.F. "or ST#T$%$NT

    The for loop is another entry controlled loop that provides a more conciseloop control structure. The syntax is :

    for(exp# ; exp$ ; exp%){

    bod* of t'e loop ; }

    #efore the first iteration" 4expr15 is evaluated. This is usually used toinitiali,e varia$les for the loop that is used to set the loop control varia$le. The4expr25 is a relational expression that determines when the loop shouldterminate. &fter each iteration of the loop" 4expr 5 is evaluated. This is usuallyused to increment or decrement the loop counters. The $ody of the loop isexecuted repeatedly till the condition in 4expr25 is satisfied. The expressionsmust $e separated $y a semicolon. &ll the expressions are optional. !f 4expr25 isleft out" it is assumed to $e 1 6i.e. True8.

    +onsider the pro$lem for printing the num$ers from 1 to n.

    The following program demonstrates the a$ove pro$lem :

    &' Demonstration o" "or statement '& inclu e *st io.+, inclu e *conio.+,

    voi main()-

    int i/ n 0clrscr() 0!rint"( $nter t+e value "or n 4 ) 0scan"( / 6n) 0!rint"( 7nT+e num;ers are 4 7n7n ) 0"or(i 1 0 i * n 0 iJJ)

    !rint"( 7t / i) 0etc+() 0

    9

    RUN 1 4

    $nter t+e value "or n 4 F

    T+e num;ers are 4

  • 8/12/2019 Chapter 05 Control

    23/23

    Control Statements 5 .23

    1 2 3 = 5 < F