Presentation is loading. Please wait.

Presentation is loading. Please wait.

EKT150 INTRODUCTION TO COMPUTER PROGRAMMING

Similar presentations


Presentation on theme: "EKT150 INTRODUCTION TO COMPUTER PROGRAMMING"— Presentation transcript:

1 EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Control Structure: Repetition Dr. Nur Hafizah Ghazali

2 Recaps... Control Structure
All programs could be written in terms of three control structures: Sequence structure Selection structure one-way selection: if if ... else switch Repetition structure

3 Today’s Outline Introduction to Repetition Structure (Loops)
Type of loops 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(“%f %f %f %f %f”, &fNum1, &fNum2, &fNum3, &fNum4, &fNum5); fSum = fNum1 + fNum2 + fNum3 + fNum4 + fNum5; fAverage = fNum / 5; If 100 numbers or 1000 numbers?

5 Repetition Structures (Loop)
Used to control the flow of a program Loops are basically repetitions or iterations used to repeat a segment of code Three statements 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 do-while statement is executed at least once

6 1. while Repetition Structure
The general form of the while statement is: while (expression) statement; To avoid an infinite loop, the loop’s body must contains statement (s) that assure the exit condition i.e. the expression in the while statement will eventually be false. while loop repeats until condition becomes false

7 Flowchart of a while statement

8 Types of while Loops 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
Count-controlled while loop uses a loop control variable in the logical expression Control variable used to count repetitions Loop control variable should be initialized before entering the while loop, and a statement in the body of the while loop should increment/decrement the control variable Definite repetition: know how many times loop will execute

10 Example : Counter-Controlled while
#include <stdio.h> int main() { int iCounter = 1; while ( iCounter <= 10 ) printf( "%d\n", iCounter ); ++iCounter; } return 0; Declare and initialize control variable value (or loop counter) test condition  A condition that tests for the final value of the control variable (i.e., whether looping should continue) Update control variable (increment/decrement)

11 Example : Counter-Controlled while
#include <stdio.h> int main() { int iCounter = 1; while ( iCounter <= 10 ) printf( "%d\n", iCounter ); ++iCounter; } return 0; 1 2 3 4 5 6 7 8 9 10

12 Example : Counter-Controlled while
Adding integers from 1 to 100 int iCount = 1; int iSum=0; while (iCount <= 100 ){ printf(“Adding %d to %d ”, iCount,iSum); iSum = iSum + iCount; printf(“ = %d”, iSum); ++iCounter; } iCounter <= 100 iSum = iSum + iCounter true false declare and initialize test condition increment

13 Example : Counter-Controlled while
Adding integers from 1 to 100 int iCount = 1; int iSum=0; while (iCount <= 100 ){ printf(“Adding %d to %d ”, iCount,iSum); iSum = iSum + iCount; printf(“ = %d”, iSum); ++iCounter; } iCounter <= 100 iSum = iSum + iCounter true false Adding 1 to 0 = 1 Adding 2 to 1 = 3 Adding 3 to 2 = 5 Adding 100 to 4950 = 5050 declare and initialize test condition increment

14 Sentinel-Controlled while Loops
An event-controlled while loop may use a special data value, sentinel, in conjunction with the logical expression to signal the loop exit. Sentinel value indicates "end of data“ As long as the sentinel value does not meet the logical expression (specified data value), the loop is executed Used when the number of repetitions is unknown and loop needs to input value repeatedly for each iteration

15 Example: Sentinel-Controlled while
Adding multiple numbers int iNumber; //declaration control variable int iSum = 0; int iCount = 0; printf("To stop enter Enter numbers : " ); scanf("%d",&iNumber);//read control variable value before enter loop while (iNumber != -999) // test condition { iSum = iSum + iNumber; //find sum of numbers entered iCount++;//counting numbers entered (increment of control variables) scanf("%d", &iNumber); //Read again control variable value } printf("\nThe sum of %d numbers is %d", iCount, iSum);

16 Example: Sentinel-Controlled while
Adding multiple numbers int iNumber; //declaration control variable int iSum = 0; int iCount = 0; printf("To stop enter Enter numbers : " ); scanf("%d",&iNumber);//read control variable value before enter loop while (iNumber != -999) // test condition { iSum = iSum + iNumber; //find sum of numbers entered iCount++;//counting numbers entered (increment of control variables) scanf("%d", &iNumber); //Read again control variable value } printf("\nThe sum of %d numbers is %d", iCount, iSum); To stop enter Enter numbers : 4 To stop enter Enter numbers : 900 To stop enter Enter numbers : 1600 To stop enter Enter numbers : -999 The sum of 3 numbers is 2504

17 Example: Sentinel-Controlled while
Evaluating grade points char cChoice; float fGradePt=0; printf(“Do want to begin? y-yes n-no: ”); scanf(“%c”, &cChoice); while ( cChoice == ‘y’) { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); } declare control variable read control variable test condition read again

18 Example: Sentinel-Controlled while
Evaluating grade points char cChoice; float fGradePt=0; printf(“Do want to begin? y-yes n-no: ”); scanf(“%c”, &cChoice); while ( cChoice == ‘y’) { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); } declare control variable read control variable test condition Do you want to begin? y-yes n-no : y Enter grade point : 2.5 Pass Continue? y-yes n-no: y Enter grade point : 1.9 Fail Continue? Y-yes n-no: n read again

19 Flag-Controlled while Loops
A flag is a boolean variable (only can be set to true or false) If a flag is used in a while loop to control the loop execution, then the while loop is referred to as a flag-controlled while loop Hence, the end-of-file-controlled while loop is a special case of a flag-controlled while loop Loop exit when expression is evaluated to false

20 Example : Flag-Controlled while
Adding multiple numbers bool proceed; // used to control the while loop int sum; // the sum of the numbers read int number; // the number read sum = 0; // initialize the sum proceed = true; // initialize the boolean variable done while ( proceed ) // while proceed is true { scanf(“%d”,&number); // read next number if ( number > 0 ) // sum number if positive sum = sum + number; // sum the number else proceed = false; // terminate the loop } printf(“Sum is %d \n”,sum);

21 Example : Flag-Controlled while
Adding multiple numbers bool proceed; // used to control the while loop int sum; // the sum of the numbers read int number; // the number read sum = 0; // initialize the sum proceed = true; // initialize the boolean variable done while ( proceed ) // while proceed is true { scanf(“%d”,&number); // read next number if ( number > 0 ) // sum number if positive sum = sum + number; // sum the number else proceed = false; // terminate the loop } printf(“Sum is %d \n”,sum); 100 200 300 400 Sum is 1000

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

23 Flowchart of a do-while loop
action(s) true condition false

24 Example: Counter-Controlled do-while
Adding integer from 1 to 10 int iCounter = 1; int iSum=0; do { printf(“Ading %d to %d =",iCounter,iSum ); iSum=iSum+iCounter; printf(“ %d\n”,iSum); } while ( ++iCounter <= 10 );

25 Example: Counter-Controlled do-while
Adding integer from 1 to 10 int iCounter = 1; int iSum=0; do { printf(“Adding %d to %d =",iCounter,iSum ); iSum=iSum+iCounter; printf(“ %d\n”,iSum); } while ( ++iCounter <= 10 ); Adding 1 to 0 = 1 Adding 2 to 1 = 3 Adding 3 to 2 = 5 Adding 10 to 45 = 55

26 Example: Sentinel-Controlled while
Evaluating grade points char cChoice; float fGradePt=0; do { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); scanf(“%c”, &cChoice); }while( cChoice == ‘y’) declare control variable read control variable test condition

27 Example: Sentinel-Controlled while
Evaluating grade points char cChoice; float fGradePt=0; do { printf(“\nEnter grade point: ”); scanf(“%f”, &fGradePt); if(fGradePt > 2.0) printf(“\nPass\n”); else printf(“\n Fail \n”); printf(“Continue? y-yes n-no: ”); scanf(“%c”, &cChoice); }while( cChoice == ‘y’) Enter grade point : 2.5 Pass Continue? n read control variable test condition

28 Infinite loop in do-while
To avoid an infinite loop, the loop body must contain a statement that ultimately makes the expression false and assures exit from the loop Another example: int iLoop = 0; do { printf (“%d ”,iLoop); iLoop = iLoop + 5; } while (iLoop <= 20); The output is:

29 Comparison between while and do-while
Example: Adding integers (a) iLoop = 11; while (iLoop <= 10) { printf("%d",iLoop); iLoop = iLoop + 5; } (b) iLoop = 11; do { printf("%d",iLoop); iLoop = iLoop + 5; }while (iLoop <= 10); In (a), the while loop, produces nothing In (b) the do…while loop, outputs the number 11

30 3. for Repetition Structure
Format when using for loops for (initialization ; loop continuation test ; increment statement) Use for loops when the repetition count is known Example: Printing integer from 1 to 10 for(iCounter = 1;iCounter <= 10;iCounter++) printf("%d\n",iCounter);

31 3. for Repetition Structure
for loops can usually be rewritten as while loops: initialization; while ( loop continuation test ) { statement; increment statement; } Initialization and increment can be comma-separated lists int iVar1, iVar2; for(iVar1=0,iVar2=0; iVar2+iVar1<=10; iVar2++,iVar1++) printf(“%d\n”,iVar2+iVar1);

32 Flowchart of for statement

33 Nested loop Loop within a loop Inner loop is performed first
Example 1: for(iLoop1=1 ; iLoop1<4 ; iLoop1++) { for(iLoop2=1 ; iLoop2<5 ; iLoop2++) printf(“%d”, iLoop2); printf(“\n”); } 1234

34 Nested loop Example 2: Program finds and prints average of three test scores, then asks if user wants to continue do { for(iCount=0; iCount <3;iCount++) { printf(“\nEnter test marks: ”); scanf(“%d”, &iMarks); iTotal=iTotal+iMarks; } fAvg=iTotal/iCount; printf(“\nAverage:%5.2f”, fAvg); printf(“\nContinue?”); scanf(“%c”, &cChoice); }while(cChoice == ‘y’);

35 Nested loop Example 2: Program finds and prints average of three test scores, then asks if user wants to continue do { for(iCount=0; iCount <3;iCount++) { printf(“\nEnter test marks: ”); scanf(“%d”, &iMarks); iTotal=iTotal+iMarks; } fAvg=iTotal/iCount; printf(“\nAverage:%5.2f”, fAvg); printf(“\nContinue?”); scanf(“%c”, &cChoice); }while(cChoice == ‘y’); Enter test marks : 78 Enter test marks : 85 Enter test marks : 82 Average : Continue? y Enter test marks : 65 Enter test marks : 73 Enter test marks : 68 Average : Continue? n

36 Exercise 1 Write a C code segment using the while loop to find the sum of the first 99 positive integers 1,2,3…99. Display the resulting sum. Declare and initialize variables used.

37 Exercise 2 Write a C program to read characters from the keyboard until a ‘q’ character is read. Use a sentinel-controlled while loop to find the number of nonblank characters read from the keyboard

38 Exercise 3 Write a program that utilizes looping to print the numbers from 1 to 10 side-by-side on the same line with 3 spaces between each number

39 Exercise 4 Finding Error
for ( x = ; x <= .0001; x += ) printf( "%.7f\n", x );

40 Exercise 5 What the following program do? #include<stdio.h>
int main() { int x,y,i,j; //declare variables printf(“Enter two integers in range 1-20:”); scanf(“%d %d”,&x,&y); //read values for x,y for(i=1;i<=y;i++){ for(j=1;j<=x;j++){ // display } //end inner for printf(“\n”); } return 0; //indicate successful termination

41 Exercise 6 Write a program that sums a sequence of integers. Assume that the first integer read with scanf specifies the number of values remaining to be entered. Your program should read only one value each time scanf is executed. A typical input sequence might be where the 5 indicates that the subsequent five values are to be summed.

42 End Week 4 - Loops Q & A!


Download ppt "EKT150 INTRODUCTION TO COMPUTER PROGRAMMING"

Similar presentations


Ads by Google