Lec 11 loops

download Lec 11 loops

of 35

Transcript of Lec 11 loops

  • 7/30/2019 Lec 11 loops

    1/35

    IntroductionIntroduction

    to Loopsto Loops

  • 7/30/2019 Lec 11 loops

    2/35

    GoalsGoals

    By the end of this unit, you shouldBy the end of this unit, you shouldunderstand understand

    basic loop concepts, includingbasic loop concepts, including

    pretest & posttest loops, looppretest & posttest loops, loopinitialization & updates, event &initialization & updates, event &start-controlled loops.start-controlled loops.

    how to program a while loop.how to program a while loop.

    how to program a do-while loop.how to program a do-while loop. how to program a for loops.how to program a for loops.

  • 7/30/2019 Lec 11 loops

    3/35

    What is a loop?What is a loop?

    AA looploop is a programming structureis a programming structure

    that allows an action to repeat untilthat allows an action to repeat until

    the program meets a given condition.the program meets a given condition.

    After eachAfter each iterationiteration of a loop, theof a loop, the

    loop checks against aloop checks against a loop controlloop control

    expressionexpression to see if the program metto see if the program met

    the given condition. If it did, the loopthe given condition. If it did, the loopstops. If not, the loop moves on tostops. If not, the loop moves on to

    the next iteration.the next iteration.

  • 7/30/2019 Lec 11 loops

    4/35

    Types of LoopsTypes of Loops

    C supports two categories ofC supports two categories of

    loops, based on where theloops, based on where the

    program tests the condition:program tests the condition: Pretest LoopsPretest Loops Post-test LoopsPost-test Loops

  • 7/30/2019 Lec 11 loops

    5/35

    Pretest LoopsPretest Loops

    With each iteration, the program tests theWith each iteration, the program tests thecondition first before executing the loopscondition first before executing the loopsblock.block.

    If the condition results toIf the condition results to truetrue, the loop, the loopcontinues and executes the block; if thecontinues and executes the block; if thecondition results tocondition results to falsefalse, the loop, the loopterminates.terminates.

    With a pretest loop, there is a chance theWith a pretest loop, there is a chance theloop may never execute once in the program.loop may never execute once in the program.

  • 7/30/2019 Lec 11 loops

    6/35

    Post-Test LoopsPost-Test Loops

    With each iteration, the programWith each iteration, the programexecutes the loops block first and testsexecutes the loops block first and testsagainst a condition.against a condition.

    If the condition tests toIf the condition tests to truetrue, the loop, the loopcontinues and executes anothercontinues and executes anotheriteration; if the condition tests toiteration; if the condition tests to falsefalse,,the loop terminates.the loop terminates.

    With a post-test loop, the loop willWith a post-test loop, the loop willalways execute at least once!always execute at least once!

  • 7/30/2019 Lec 11 loops

    7/35

    Pretest vs. Post-Test LoopsPretest vs. Post-Test Loops

  • 7/30/2019 Lec 11 loops

    8/35

    Loop InitializationLoop Initialization

    Programs typically require some type ofPrograms typically require some type ofpreparation before executing loops.preparation before executing loops.

    Loop initializationLoop initialization, which happens before a, which happens before a

    loops first iteration, is a way to prepare theloops first iteration, is a way to prepare theloop..loop..

  • 7/30/2019 Lec 11 loops

    9/35

    Updating a LoopUpdating a Loop

    A loop update is what happens inside aA loop update is what happens inside aloops block that eventually causes theloops block that eventually causes theloop to satisfy the condition, thus endingloop to satisfy the condition, thus ending

    the loop.the loop. Updating happens during each loopUpdating happens during each loop

    iteration.iteration.

    Without a loop update, the loop would beWithout a loop update, the loop would bean infinite loop.an infinite loop.

  • 7/30/2019 Lec 11 loops

    10/35

    Initialization & UpdatingInitialization & Updating

  • 7/30/2019 Lec 11 loops

    11/35

    Concept of aConcept of a

    start-Controlled Loopstart-Controlled Loop

  • 7/30/2019 Lec 11 loops

    12/35

    Loop Comparison in aLoop Comparison in a

    start-Controlled Loopstart-Controlled Loop

  • 7/30/2019 Lec 11 loops

    13/35

    TheThewhilewhile LoopLoop

  • 7/30/2019 Lec 11 loops

    14/35

    Example of while loopExample of while loop#include#include

    #include#includeint main()int main()

    {{

    int start, end;int start, end;

    scanf("%d",&end);scanf("%d",&end);

    start = 0;start = 0;

    while ( start < end)while ( start < end)

    {{start++;start++;

    printf("%d\n", start);printf("%d\n", start);

    }}

    return 0;return 0;

    If we input value

    of end as 10 then

    output will be 1 to

    10

  • 7/30/2019 Lec 11 loops

    15/35

    ExampleExample#include#include

    int main()int main()

    { int i;{ int i;

    i = 0;i = 0;

    while(i++ < 5)while(i++ < 5){ printf("%d\n", i);{ printf("%d\n", i);

    }}

    printf("\n");printf("\n");

    i = 0;i = 0;while(++i < 5)while(++i < 5)

    { printf("%d\n", i); }{ printf("%d\n", i); }

    return 0; }return 0; }

    The output of the postfix and

    prefix increment example willlook like this:

    1

    2

    3

    4

    5

    1

    2

    3

    4

  • 7/30/2019 Lec 11 loops

    16/35

    TheThe forfor LoopLoop

    AA forfor loop is a pretest loop that includes threeloop is a pretest loop that includes threeexpressions in its header:expressions in its header: Loop initialization statementLoop initialization statement Limit test expressionLimit test expression

    Loop update statementLoop update statement

    The for loop is often used as a start-controlledThe for loop is often used as a start-controlledloop since we can accurately predict theloop since we can accurately predict themaximum number of iterations.maximum number of iterations.

  • 7/30/2019 Lec 11 loops

    17/35

    TheThe forfor LoopLoop

  • 7/30/2019 Lec 11 loops

    18/35

    ComparingComparingwhilewhile withwith forfor

  • 7/30/2019 Lec 11 loops

    19/35

    ComparingComparingwhilewhile withwith forfor

    i = 1;i = 1;

    sum =0;sum =0;

    while (i

  • 7/30/2019 Lec 11 loops

    20/35

    Example of for loopExample of for loopmain ( )main ( )

    {{

    int p, n, count ;int p, n, count ;

    float r, si ;float r, si ;

    for ( count = 1 ; count

  • 7/30/2019 Lec 11 loops

    21/35

    ExampleExample

    #include #include #include#include

    void main()void main()

    {{

    int i = 0, j = 8;int i = 0, j = 8;

    printf("Times 8 Table\n");printf("Times 8 Table\n");

    for(i = 0; i

  • 7/30/2019 Lec 11 loops

    22/35

    NestedNested forfor LoopsLoops

    We can nest any statement, evenWe can nest any statement, even

    anotheranotherforfor loop, inside the body ofloop, inside the body of

    a parenta parent forfor loop.loop. When we nest a childWhen we nest a child forfor loop, itloop, it

    iterates all of its cycles for eachiterates all of its cycles for each

    iteration of the parent.iteration of the parent.

  • 7/30/2019 Lec 11 loops

    23/35

    Example of nested for loopExample of nested for loop /* Demonstration of nested loops *//* Demonstration of nested loops */

    main( )main( )

    {{

    int r, c, sum ;int r, c, sum ;

    for ( r = 1 ; r

  • 7/30/2019 Lec 11 loops

    24/35

    TheThe do whiledo while LoopLoop

    C implements a post-test loop using aC implements a post-test loop using astructure called astructure called a do whiledo while loop.loop.

    In theIn the do whiledo while, the loop begins with, the loop begins with

    the keywordthe keyword dodo, followed by the body,, followed by the body,followed by the keywordfollowed by the keywordwhilewhile and theand theloop expression.loop expression.

    A semi-colon (A semi-colon (;;) follows the loop) follows the loopexpression.expression.

  • 7/30/2019 Lec 11 loops

    25/35

    TheThe do whiledo while LoopLoop

  • 7/30/2019 Lec 11 loops

    26/35

    Example of do-whileExample of do-while/* Execution of a loop an unknown number of time*//* Execution of a loop an unknown number of time*/

    main( )main( )

    {{

    char another ;char another ;

    int num ;int num ;

    dodo

    {{

    printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

    scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;printf ( "square of %d is %d", num, num * num ) ;printf ( "square of %d is %d", num, num * num ) ;

    printf ( "\nWant to enter another number y/n " ) ;printf ( "\nWant to enter another number y/n " ) ;

    scanf ( " %c", &another ) ;scanf ( " %c", &another ) ;

    } while ( another == 'y' ) ;}} while ( another == 'y' ) ;}

    Output:

    Enter a number 5

    square of 5 is 25

    Want to enter another number y/n yEnter a number 7

    square of 7 is 49

    Want to enter another number y/n n

  • 7/30/2019 Lec 11 loops

    27/35

    Same using for loopSame using for loop

    /* odd loop using a for loop *//* odd loop using a for loop */main( )main( )

    {{

    char another = 'y' ;char another = 'y' ;

    int num ;int num ;

    for ( ; another == 'y' ; )for ( ; another == 'y' ; )

    {{

    printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

    scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;

    printf ( "square of %d is %d", num, num * num ) ;printf ( "square of %d is %d", num, num * num ) ;

    printf ( "\nWant to enter another number y/n " ) ;printf ( "\nWant to enter another number y/n " ) ;

    scanf ( " %c", &another ) ;scanf ( " %c", &another ) ;

  • 7/30/2019 Lec 11 loops

    28/35

    Same using while loopSame using while loop/* odd loop using a while loop *//* odd loop using a while loop */

    main( )main( ){{

    char another = 'y' ;char another = 'y' ;

    int num ;int num ;

    while ( another == 'y' )while ( another == 'y' )

    {{

    printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

    scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;printf ( "square of %d is %d", num, num * num ) ;printf ( "square of %d is %d", num, num * num ) ;

    printf ( "\nWant to enter another number y/n " ) ;printf ( "\nWant to enter another number y/n " ) ;

    scanf ( " %c", &another ) ;scanf ( " %c", &another ) ;

    }}}}

  • 7/30/2019 Lec 11 loops

    29/35

    ComparingComparing

    do whiledo while withwithwhilewhile

  • 7/30/2019 Lec 11 loops

    30/35

    TheThebreakbreak Statement in LoopsStatement in Loops

    We often come across situations where we wantWe often come across situations where we want

    to jump out of a loop instantly, without waiting toto jump out of a loop instantly, without waiting to

    get back to the conditional test.get back to the conditional test.

    The keywordThe keyword break allows us to do this.break allows us to do this. When break isWhen break is encountered inside any loop,encountered inside any loop,

    control automatically passes to the firstcontrol automatically passes to the first

    statement after the loop.statement after the loop.

  • 7/30/2019 Lec 11 loops

    31/35

    Example of breakExample of break Write a program to determine whether a number isWrite a program to determine whether a number is

    prime or not. A prime number is one, which isprime or not. A prime number is one, which is

    divisible only by 1 or itself.divisible only by 1 or itself.

    All we have to do to test whether a number is prime orAll we have to do to test whether a number is prime or

    not, is to divide it successively by all numbers from 2 tonot, is to divide it successively by all numbers from 2 to

    one less than itself.one less than itself.

    If remainder of any of these divisions is zero, the numberIf remainder of any of these divisions is zero, the number

    is not a prime. If no division yields a zero then theis not a prime. If no division yields a zero then the

    number is a prime number.number is a prime number.

  • 7/30/2019 Lec 11 loops

    32/35

    ExampleExamplemain( )main( )

    {int num, i ;{int num, i ;

    printf ( "Enter a number " ) ;printf ( "Enter a number " ) ;

    scanf ( "%d", &num ) ;scanf ( "%d", &num ) ;

    i = 2 ;i = 2 ;

    while ( i

  • 7/30/2019 Lec 11 loops

    33/35

    ExampleExample

    The keywordThe keyword breakbreakbreaks thebreaks the

    control onlycontrol only

    from the while infrom the while in

    which it is placed.which it is placed.

    main( )

    {int i = 1 , j = 1 ;

    while ( i++

  • 7/30/2019 Lec 11 loops

    34/35

    TheThe continuecontinue StatementStatement

    In some programming situations we want to takeIn some programming situations we want to take

    the control to the beginning of the loop,the control to the beginning of the loop,

    bypassing the statements inside the loop,bypassing the statements inside the loop,

    which have not yet been executed. The keywordwhich have not yet been executed. The keywordcontinue allowscontinue allows us to do this.us to do this.

    WhenWhen continue is encountered inside anycontinue is encountered inside any

    loop,loop, control automatically passes to thecontrol automatically passes to the

    beginning of the loop.beginning of the loop.

  • 7/30/2019 Lec 11 loops

    35/35

    Example of continue statementExample of continue statement

    main( )main( )

    {{

    int i, j ;int i, j ;

    for ( i = 1 ; i