Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 4 – Repetition Structures / Loops

Similar presentations


Presentation on theme: "Week 4 – Repetition Structures / Loops"— Presentation transcript:

1 Week 4 – Repetition Structures / Loops
EKT 150 SEM 1 10/11

2 Outline Introduction While loops Do-while loops For loops Nested loops
Three types of while loops Do-while loops For loops Nested loops EKT 120 SEM II 09/10

3 Outline Introduction While loops Do-while loops For loops Nested loops
Three types of while loops Do-while loops For loops Nested loops

4 Why Need Loops ? Suppose we want to add five numbers and find the average. From what you have learned so far, you could proceed as follows scanf(“%d %d %d %d %d”, &num1, &num2, &num3, &num4,&num5); sum = num1 + num2 + num3 + num4 + num5; average = sum / 5; If 100 numbers, 1000 numbers?

5 Repetition (Loop)‏ Used to control the flow of a program
Loops are basically repetitions or iterations used to repeat a segment of code Three statements can be used to implement loops in C while statement do-while statement for statement while and for statements are similar in implementation, but have different syntax The do-while statement is different - the following code is executed at least once

6 The while loop structure
The general form of the while statement is: while (expression)‏ statement; To avoid an infinite loop, make sure that the loop’s body contains statement (s) that assure that the exit condition i.e. the expression in the while statement will eventually be false. while loop repeated until condition becomes false

7 Flowchart of a while statement

8 The while loop structure-cont
There are basically three types of while loops: Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop

9 Counter-Controlled while Loops
Definite repetition: know how many times loop will execute Control variable used to count repetitions Example: int counter = 1; // declare and initialize while ( counter <= 10 ) // test condition { printf( "%d\n", counter ); ++counter; // update } Requirement: 1. Declare and initialize control variable value (or loop counter)‏ 2. A condition that tests for the final value of the control variable (i.e., whether looping should continue)‏ 3. Update control variable (incr/decr)‏

10 Counter-Controlled while Loops
Another example: int product = 2; while ( product <= 1000 ) product = 2 * product; declare and initialize test condition increment product <= 1000 product = 2 * product true false

11 Example: A class of ten students took a quiz
Example: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz Pseudocode: Set total to zero Set grade counter to one While grade counter is less than or equal to ten Input the next grade Add the grade into the total Add one to the grade counter Set the class average to the total divided by ten Print the class average

12 1. Initialize Variables 2. Execute Loop 3. Output results
1 /* Fig. 3.6: fig03_06.c 2 Class average program with 3 counter-controlled repetition */ 4 #include <stdio.h> 5 6 int main()‏ 7 { 8 int counter, grade, total, average; 9 10 /* initialization phase */ 11 total = 0; 12 counter = 1; 13 14 /* processing phase */ 15 while ( counter <= 10 ) { printf( "Enter grade: " ); scanf( "%d", &grade ); total = total + grade; counter = counter + 1; 20 } 21 22 /* termination phase */ 23 average = total / 10; 24 printf( "Class average is %d\n", average ); 25 26 return 0; /* indicate program ended successfully */ 27 } 1. Initialize Variables 2. Execute Loop 3. Output results OUTPUT Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81

13 Sentinel-Controlled while Loops
Indefinite repetition Used when number of repetitions not known and loop needs to input value repeatedly for each iteration Sentinel value indicates "end of data“

14 Sentinel-Controlled while Loops-cont
Requirement: 1. Read control variable value before enter loop 2. A condition that tests control variable’s validity (i.e., whether looping should continue)‏ 3. Read again control variable before end of loop Example: int number, count, sum; printf(“To stop enter Enter positive numbers : " ); scanf(“%d”, &number); while (number != -999)‏ { sum = sum + number; //find sum of numbers entered count++; //count how many numbers entered } printf(“\nThe sum of %d numbers is %d“, count, sum); Sentinel value

15 Sentinel-Controlled while Loops-cont
Another example: char choice; printf(“Continue?y-yes n-no :”); scanf(“%c”, &choice); while ( choice == ‘y’)‏ { printf(“\nEnter grade point:”); scanf(“%f”, &grade_pt); if(grade_pt > 2.0)‏ printf(“\nPass); } read control variable test condition read again

16 1. Initialize Variables 2. Get user input 2.1 Perform Loop
1 /* Fig. 3.8: fig03_08.c 2 Class average program with 3 sentinel-controlled repetition */ 4 #include <stdio.h> 5 6 int main()‏ 7 { 8 float average,total; /* new data type */ 9 int counter, grade,; 10 11 /* initialization phase */ 12 total = 0; 13 counter = 0; 14 15 /* processing phase */ 16 printf( "Enter grade, -1 to end: " ); 17 scanf( "%d", &grade ); 18 19 while ( grade != -1 ) { total = total + grade; counter = counter + 1; printf( "Enter grade, -1 to end: " ); scanf( "%d", &grade ); 24 } 1. Initialize Variables 2. Get user input 2.1 Perform Loop

17 3. Calculate Average 3.1 Print Results Program Output
25 26 /* termination phase */ 27 if ( counter != 0 ) { average = total / counter; printf( "Class average is %.2f", average ); 30 } 31 else printf( "No grades were entered\n" ); 33 34 return 0; /* indicate program ended successfully */ 35 } 3. Calculate Average 3.1 Print Results Program Output Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50

18 Flag-Controlled while Loops
Uses a boolean variable to control the loop. Loop exit when expression is evaluated to false. Set to false Requirement: 1. Set control variable to false before loop 2. A condition that tests control variable. If expr evaluated to true, loop continue 3. A decision structure to test value validity 4. Set control variable to true to indicate found bool found = false; while (!found) { printf(“Enter number between 1 and 200:”); scanf(%d”, &guess); if ((guess>= 88) &&(guess <=128))‏ {found = true; printf(“\nBINGO!”);} } test condition Decision structure Set to true

19 The do-while Repetition Structure
Similar to the while structure Condition for repetition tested after the body of the loop is performed All actions are performed at least once Expression can be written as count-controlled or sentinel-controlled Format: do { statement; } while ( condition );

20 Flowchart of a do-while structure
true false action(s)‏ condition

21 The do-while Repetition Structure
Example : prints the integers from 1 to 10 int counter = 1; do { printf( "%d ", counter ); } while (++counter <= 10); Another example: do{ printf(“\nEnter grade point:”); scanf(“%f”, &grade_pt); if(grade_pt > 2.0)‏ printf(“\nPass); printf(“Continue?y-yes n-no :”); scanf(“%c”, &choice); }while ( choice == ‘y’)‏ counter-controlled sentinel-controlled

22 The do-while Repetition Structure
To avoid an infinite loop, make sure that the loop body contains a statement that ultimately makes the expression false and assures that it exits Another example: int i = 0; do { printf(“%d\t”,i); i = i + 5; } while (i <= 20); The output is:

23 The do-while Looping Structure (Example)‏
Example: Consider the following two loops a) i=11; while(i<=10); { printf(“%d”,i); i=i+5; } b) i=11; do { printf(“%d”,i); i=i+5; } while(i<=10);

24 The do-while Looping Structure (Example)‏
In (a), the while loop, produces nothing In (b) the do...while loop, outputs the number 11

25 The for Repetition Structure
Format when using for loops for ( initialization; loopContinuationTest; increment statement)‏ Use for loops when already know how many times to repeat Example: for(counter = 1; counter <= 10;counter++ )‏ printf( "%d\n", counter ); Prints the integers from one to ten

26 The for Repetition Structure
For loops can usually be rewritten as while loops: initialization; while ( loopContinuationTest ) { statement; increment statement; } Initialization and increment Can be comma-separated lists Example: for (int i = 0, j = 0; j + i <= 10; j++, i++)‏ printf( "%d\n", j + i );

27 Flow of a for statement

28 Nested loop Loop within a loop Inner loop is performed first E.g.
for(i=1;i<4;i++){ for(j=1;j<5;j++)‏ printf(“%d”, j); printf(“\n”);} Output 1234

29 Nested loop Another example:
Program find and print avg of three test scores, then asks whether want to continue do{ for(count=0; count <3;count++)‏ { printf(“\nEnter test marks:”); scanf(“%d”, marks); total=total+marks; } avg=total/count; printf(“\nAverage:%5.2f”, avg); printf(“\nContinue?”); scanf(“%c”, &choice); }while(choice == ‘y’);

30 End Week 4- Loops Q & A!


Download ppt "Week 4 – Repetition Structures / Loops"

Similar presentations


Ads by Google