9. lecture 6 eio oct2012

Upload: miller

Post on 02-Apr-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    1/25

    Lectu re 6

    Construct 3 Repetition / looping

    By Prof. Elijah OmwengaOctober 2012

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    2/25

    In t roduct ion to Loop ing

    Loops cause a section of your program to berepeated a certain number of times. Therepetition continues while a condition is true.

    When a condition becomes false, the loopends and control is passed to the statementsfollowing the loop. If a loop continuesforever, it is called an infinite loop.

    In looping, a sequence of statements isexecuted until some condition for thetermination of the loop are satisfied.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    3/25

    A program loop therefore consists of twosegments:

    1.Control statement.2.Body of the loop

    The control statement sets certain conditionsand then directs the repeated execution ofthe statements contained in the body of theloop.

    There are three kinds of loops in C: the forloop, the while loop, and the do loop.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    4/25

    The for loopThe forloop is an entry controlled loop that provides aconcise loop control. The general form of the loop is:

    for (initialisation; test condition; increment){

    statement;statement;

    } // No semicolon here

    The execution of the forstatementis done as, by firstly

    initialising the control variables using assignmentstatements such as i=0. the variables i is known as loopcontrol variable.

    The value of the control variable is tested using the testcondition. See flowchart below:

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    5/25

    The for loop

    The body of the loop can contain one ormultiple statements. The brace {} areused to group the multiple statements.

    However it is a good programming practiceto use braces even if there is only onestatement in the body of the loop.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    6/25

    The for loop

    Test

    Body of loop

    Exit

    True

    False

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    7/25

    The test condition is a relational expression,such as i

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    8/25

    #include void main()

    { int count, number, sum;double average;sum =0;for (count=0;count

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    9/25

    The while loop

    The test condition is evaluated first and if thecondition is true, the body of the loop is executedzero or more times.

    After execution of the body, the test condition is

    once again evaluated and if it is true, the body isexecuted once again.

    This process of repeated execution of the bodycontinues until the test condition finally become

    false. On exit, the program continues with thestatement immediately after the body of the loop.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    10/25

    whi le loop

    True

    Test

    Body of loop.Increment count

    Exit

    True

    False

    initialize count

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    11/25

    The general form of the while loop is:

    while (test-condition){

    statement;statement;

    } // No semicolon here

    NB:The difference between while loop and the for loop

    is that the forloop does something a fixed numberof times while the while loop can be used where thenumber of loops is not known.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    12/25

    #include void main(){

    int count, number, sum;double average;sum =0;count=0;

    while (count

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    13/25

    The do .. wh i le loop

    Unlike the while loop in which a condition istested before the loop is executed.

    In do.. while (condition), the testing is doneafter the body of the loop is executed at leastonce.

    This means that the execution is one ormore times.

    See the flowchart on the next slide...

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    14/25

    Do whi le loop

    Test

    do{Body of loop.

    }

    Exit

    True

    False

    initialize count

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    15/25

    The general form of the do loop is:do{

    statement;statement;

    } // No semicolon here

    while (test-condition); // semi colons here

    On reaching the do statement, the programproceeds to evaluate the body of the loop first. Atthe end of the loop, the test condition in the while

    statement is evaluated. If the condition is true, theprogram continues to evaluate the body of the looponce again.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    16/25

    This process continues as long as thecondition is true.

    When the condition becomes false, the loopwill be terminated and the control goes to thestatement that appears immediately after thewhile statement.

    Since the test condition is evaluated at thebottom of the loop, the do. Whileconstruct provides an exit controlled loopand therefore the body of the loop is always

    executed at least once.

    do while loop

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    17/25

    #include

    void main()

    {

    int count, number, sum;double average;

    sum =0;

    count=0;

    do

    {

    printf ("Enter a number");

    scanf("%d", &number);

    sum=sum+number;

    count++;

    }

    while (count

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    18/25

    Sentinel controlled loop

    In a Sentinel-Controlled loop, a special value called asentinel value is used to change the loop control

    expression from true to false.

    For example, when reading data we may indicate the "end

    of data" by a special value, like -1 and 999. The controlvariable is called sentinel variable.

    A sentinel-Controlled loop is often called indefinite

    repetition loop because the number of repetitions is not

    known before the loop begins executing.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    19/25

    Sent inel contro l led loop

    #include

    void main()

    {

    int number, count,sum;

    double average;

    sum =0;count=0;

    printf ("Enter a number ");

    scanf("%d", &number);

    while (number!=-1)

    {

    sum=sum+number;

    printf ("Enter a number ");

    scanf("%d", &number);

    count++;

    }

    if (count>0)

    {

    average=(double)sum/count;

    printf("The Average is %7.2lf\n",

    average);

    }

    else

    printf("Sum is %d\n", sum);

    }

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    20/25

    Break and continue

    Break and continue are used to alter the flow of control. Break is used to exit from a loop (for, while, or do) or a

    switch, passing control to the first statement outside the loop

    or switch. A break within a loop should always be protected

    within an if statement which provides the test to control the

    exit condition. Continue is similar to break but only works within loops

    where its effect is to force an immediate jump to the loop

    Boolean test.

    In a while loop, jump to the test statement. In a do while

    loop, jump to the test statement. In a for loop, jump to thetest, and perform the iteration. Like a break, continue should

    be protected by an if statement.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    21/25

    Break example: Prime number testing

    Write your own program that tests if the given number is

    prime number.#include #include void main() {

    int i, n, prime; prime=1; // prime is trueprintf("Input natural number :");scanf("%d", &n);for( i=2; i

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    22/25

    Prime numbers

    To test if a numbern is prime, we could loop through 2 ton - 1 and test whether each number divides exactly into n((n % test) == 0). If any of them do, the number is notprime.

    However, since by definition any number which is notprime can be divided by at least one other prime number,a more efficient way to do it is to test only the primenumbers less than n.

    Therefore, our program maintains a list of prime numbersalready found, and uses that to test n.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    23/25

    Use of break and continue

    Write a program that reads integers. If the given number issmaller than zero, program should print error messageand stop reading numbers.

    If the given number is bigger than 100, it should beskipped and program should read another number. Allother numbers should be red and printed. Program must

    stop reading numbers when 0 or error shows up.

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    24/25

    Break and con t inue

    #include void main() {int x;

    do {printf ("Input number :\n");scanf("%d", &x );if (x < 0) {

    printf("Not allowed value\n");break; /* escapes the loop */

    }

    if (x > 100) {printf("Skipping the value\n");

    continue;/* jumps to second iteration */}printf ("Given number is : %d", x);

    } while (x != 0);}

  • 7/27/2019 9. Lecture 6 EIO Oct2012

    25/25

    Mathematical OperatorsOperator Name /Function Description

    + Addition

    The result of addition of two integers is an

    integer. The result of addition of a float and aninteger is a float. A float plus a float results in a

    float

    - Subtraction

    The result of subtraction of two integers is an

    integer. The result of subtraction of a float and an

    integer is a float. A float minus a float results in a

    float

    * Multiplication

    Multiplication of two integers results in an

    integer. The result of multiplication of a float and

    an integer is a float. A float times a float results in

    a float

    / DivisionDivision of two integers results in an integer. Anyremainder is lost. The result of division of a float

    and an integer is a float. A float divided by a float

    results in a float

    % modulusActs on integers. Returns the remainder of an

    integer division