143_btt121_pt1222_905_941_chapter3

Upload: aljawad14

Post on 13-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    1/9

    while, for, do-while

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    2/9

    provide ability to execute the same code multiple times

    three constructs while statement

    do-while statement

    for statement

    2

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    3/9

    syntaxwhile

    (expression)

    action semantics

    if expressionis truethen execute action

    repeat this process untilexpressionevaluates tofalse

    actionis either asingle statement or ablock

    3

    expression

    action

    true false

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    4/9

    syntaxdoaction

    while(expression);

    semantics execute action if expressionis true

    then execute actionagain

    repeat this process untilexpressionevaluates tofalse

    actionis either a singlestatement or a block

    4

    action

    true

    false

    expression

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    5/9

    syntaxfor(init_statement;expression;post_statement)

    action semantics

    execute init_statement evaluate expressionif true

    execute action execute post_statement repeat

    examplefor (int i = 0; i < 20; ++i)

    cout

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    6/9

    what is idiom again?

    often need to iterate while keep track of some value across

    iterationsmaximum found, sum, if all positive, etc.

    idiom

    before loop declare variable to keep track, initialize it

    inside loop, update tracking variable, use branching ifnecessary to examine

    after loop, use the tracking variable that accumulated theresult

    example:

    cout > n; max = n;

    while (n != 0 ) {cin >> n;

    if ( n > max) max = n;

    }

    cout

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    7/9

    break- exits innermost loop

    int sum=0;while(sum < 100) {

    int i; cin >> i;if (i< 0) {

    cout > intVar;

    if(intVar < 0) continue;sum +=i;}

    avoid break/continuewith loops as they make code less readable (avoidregular loop exit) first try to code loop without them

    7

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    8/9

    iterative constructs can be nested: oneiterative construct may be inside the body ofanother

    example:for (int i = 0; i < 10; ++i) // outer loopfor (int j = 0; j < 10; ++j) // inner loop

    cout

  • 7/26/2019 143_BTT121_PT1222_905_941_chapter3

    9/9

    key points make sure there is a statement that will

    eventually nullify the iteration criterion (i.e.,the loop must stop)

    make sure that initialization of any loopcounters or iterators is properly performed

    have a clear purpose for the loop

    document the purpose of the loop and how thebody of the loop advances the purpose of the loop

    9