EKT150 INTRODUCTION TO COMPUTER PROGRAMMING Control Structure: Repetition Dr. Nur Hafizah Ghazali hafizahghazali@unimap.edu.my
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
Today’s Outline Introduction to Repetition Structure (Loops) Type of loops while loops do-while loops for loops Nested loops
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?
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
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
Flowchart of a while statement
Types of while Loops There are basically three types of while loops: Counter-controlled while loop Sentinel-controlled while loop Flag-controlled while loop
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
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)
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
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
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
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
Example: Sentinel-Controlled while Adding multiple numbers int iNumber; //declaration control variable int iSum = 0; int iCount = 0; printf("To stop enter -999. 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);
Example: Sentinel-Controlled while Adding multiple numbers int iNumber; //declaration control variable int iSum = 0; int iCount = 0; printf("To stop enter -999. 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 -999. Enter numbers : 4 To stop enter -999. Enter numbers : 900 To stop enter -999. Enter numbers : 1600 To stop enter -999. Enter numbers : -999 The sum of 3 numbers is 2504
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
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
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
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);
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
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 );
Flowchart of a do-while loop action(s) true condition false
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 );
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
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
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
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: 0 5 10 15 20
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
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);
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);
Flowchart of for statement
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
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’);
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 : 81.67 Continue? y Enter test marks : 65 Enter test marks : 73 Enter test marks : 68 Average : 68.67 Continue? n
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.
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
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
Exercise 4 Finding Error for ( x = .000001; x <= .0001; x += .000001 ) printf( "%.7f\n", x );
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++){ printf(“@”); // display output @ } //end inner for printf(“\n”); } return 0; //indicate successful termination
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 5 100 200 300 400 500 where the 5 indicates that the subsequent five values are to be summed.
End Week 4 - Loops Q & A!