Problem Solving and Program Design in C Chap
Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin
CSIE@NUTN Repetition • Loop – The repetition of steps in a program • Loop body – The statements that are repeated in the loop Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 2
CSIE@NUTN Repetition (Cont. ) Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 3
CSIE@NUTN Loop Kinds C Implementation Structures Kind When Used Counting loop We can determine before loop execution exactly how many loop repetitions will be needed to solve the problem while for Sentinel-controlled loop Input of a list of data of any length ended by a special value while, for Endfile-controlled loop Input of a single list of data of any length from a data file while, for Input validation loop Repeated interactive input of a data value do-while until a value within the valid range is entered General conditional loop Repeated processing of data until a desired condition is met Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 while, for 4
CSIE@NUTN Counting Loop • Counter-controlled loop (Counting loop) Set loop control variable to an initial value of 0 while loop control variable < final value …… Increase loop control variable by 1 – A loop whose required number of iterations can be determined before loop execution begins Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 5
CSIE@NUTN while Statement • SYNTAX Example while (loop repetition condition) statement Dr. Chow-Sing Lin /* Display N asterisks. */ count_star = 0; while (count_star < N) { printf(“*”); count_star = count_star + 1; } Repetition and Loop Statement - CH 5 6
CSIE@NUTN while Statement (Cont. ) • Computes and displays the gross pay for seven employees Loop repetition condition statement After seven weekly pay amounts are displayed – Count_emp : loop control variable Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 7
CSIE@NUTN while Statement (Cont. ) Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 8
CSIE@NUTN Exercises • Predict the output of this program fragment : i = 0; while (i <= 5) { printf(“%3 d %3 dn”, i, 10 – i); i = i + 1; } Dr. Chow-Sing Lin output Repetition and Loop Statement - CH 5 0 10 1 9 2 8 3 7 4 6 5 5 9
CSIE@NUTN Loop control variable • Determine whether the loop body is repeated • Initialization – count_emp is set to an initial value of 0 before the while statement is reached • Initialized to 0 • Testing – count_emp is tested before the start of each loop repetition • Called an iteration or a pass • Updating – count_emp is updated (its value increased by 1) during each iteration Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 10
CSIE@NUTN Infinite loop • If the loop control variable is not updated – The loop will execute “forever” • A loop that executes forever Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 11
Computing a Sum in a Loop CSIE@NUTN Accumulator : a variable used to store a value being computed in increments during the execution of a loop Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 12
CSIE@NUTN Enter number of employees> 3 Hours> 50 Rate> $5. 25 Pay is $262. 50 Hours> 6 Rate> $5. 00 Pay is $30. 00 Hours> 15 Rate> $7. 00 Pay is $105. 00 All employees processed Total payroll is $ 397. 50 Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 13
CSIE@NUTN Computing a Sum in a Loop (Cont. ) Statement hours rate pay total_pay count_emp ? ? ? 0. 0 0 true count_emp < number_emp scanf (“%lf”, &hours); 50. 0 get hours 5. 25 scanf (“%lf”, &rate); get rate 262. 5 pay = hours * rate; find pay 262. 5 total_pay = total_pay + pay = hours * rate; Dr. Chow-Sing Lin Increment count_emp true count_emp < number_emp scanf (“%lf”, &rate); add to total_pay 1 count_emp = count_emp +1 scanf (“%lf”, &hours); Effect 6. 0 get hours 5. 0 get rate 30. 0 Repetition and Loop Statement - CH 5 find pay 14
CSIE@NUTN Computing a Sum in a Loop (Cont. ) Statement hours rate pay total_pay count_emp 292. 5 total_pay = total_pay + pay add to total_pay 2 count_emp = count_emp +1 scanf (“%lf”, &rate); pay = hours * rate; total_pay = total_pay + pay 15. 0 get hours 7. 0 get rate 105. 0 find pay 397. 5 add to total_pay 3 count_emp = count_emp +1 Dr. Chow-Sing Lin Increment count_emp true count_emp < number_emp scanf (“%lf”, &hours); Effect Repetition and Loop Statement - CH 5 Increment count_emp 15
CSIE@NUTN Computing a Product in a loop • Example 5. 2 – The loop that follows multiplies data items together as long as the product remains less than 10, 000 – Before asking for the next data value, it displays the product calculated so far /* Multiply data while product remains less than 10000 */ product = 1; while (product < 10000) { printf(“%dn, product); /* Display product so far */ printf(“Enter next item> “); scanf(“%d”, &item); product = product * item; /* Update product */ } Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 16
CSIE@NUTN Compound Assignment Operators • variable = variable op expression – op is a C arithmetic operator – Increments and decrements of loop counters • count_emp = count_emp + 1; • time = time – 1; – Statements accumulating a sum or a computing a product in a loop • total_pay = total_pay +pay; • product = product * item; Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 17
Compound Assignment Operators (Cont. ) Statement with Simple Assignment Operator Equivalent Statement with Compound Assignment Operator count_emp = count_emp + 1; count_emp += 1; time =time – 1 ; time -= 1; total_time = total_time + time; total time += time; product = product * item; product *= item; n = n * (x + 1); n *= x + 1; Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 CSIE@NUTN 18
CSIE@NUTN The for Statement • loop control components – Initialization of the loop control variable – Test of the loop repetition condition – Change (update) of the loop control variable • Syntax for (initialization expression; loop repetition condition; update expression) statement Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 19
CSIE@NUTN The for Statement (Cont. ) Example for (count_emp = 0 ; count_emp < number_emp; count_emp += 1) /* initialization */ /* loop repetition condition */ /* update */ Example /* Display N asterisks. */ for (count_star = 0; count_star < N; count_star += 1) printf (“*”); Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 20
CSIE@NUTN Increment and Decrement Operator • Increment operator “++” – The value of its operand is incremented by one • Prefix increment – “++” is placed immediately in front of its operand (++a) – The value of the expression is the variable ‘s value after incrementing • Postfix increment – “++” comes immediately after the operand (a++) – the expression’s value is the value of the variable before it is incremented Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 21
Increment and Decrement Operator (Cont. ) CSIE@NUTN • Given an initial value of 2 in i Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 22
CSIE@NUTN Function to Compute Factorial Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 23
CSIE@NUTN Increments and Decrements Other Than 1 • Example 5. 4 – Temperature conversions from 10 degrees Celsius to -5 degrees Celsius – The values of the constant macros named CBEGIN and CLIMIT – Loop update step • Subtracts CSTEP(5) from Celsius – When Celsius becomes less than CLIMIT • Loop exit (Celsius is -10) Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 24
CSIE@NUTN Figure 5. 8 Displaying a Celsius-to. Fahrenheit Conversion Table Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 25
CSIE@NUTN Review Question I • Trace the execution of the loop –n=8 – Show values of odd and sum • After the update of the loop counter for each iteration sum = 0; for (odd = 1; odd < n; odd += 2) sum = sum + odd; printf(“Sum of positive odd numbers less than %d is %d. n”, n, sum); Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 26
CSIE@NUTN Review Question I (Cont. ) For n = 8 : Statement odd sum = 0; odd = 1 sum 0 1 1 < 8 is true sum += odd; 1 3 3 < 8 is true sum += odd; 4 5 5 < 8 is true sum += odd; odd < n; Dr. Chow-Sing Lin sum = 1 + 3 odd = 3 + 2 odd < n; odd += 2 sum = 0 + 1 odd = 1 + 2 odd < n; odd += 2 Initialize sum to 0 Initialize odd to 1 odd < n; odd += 2 Effect 9 7 sum = 4 + 5 odd = 5 + 2 7 < 8 is true Repetition and Loop Statement - CH 5 27
CSIE@NUTN Review Question I (Cont. ) Statement odd sum += odd; odd += 2 odd < n; sum 16 9 Effect sum = 9 + 7 odd = 7 + 2 9 < 8 is false Exit loop printf (“Sum of… Dr. Chow-Sing Lin Output : Sum of positive odd numbers less than 8 is 16 Repetition and Loop Statement - CH 5 28
CSIE@NUTN Review Question II • Rewrite the code – No increment / decrement operator appears in an expression with another arithmetic operator n = ++i * --j; m = i + j--; p = i + j; Dr. Chow-Sing Lin Rewrite ++i; --j; n = i * j; m = i + j; j--; p = i + j; Repetition and Loop Statement - CH 5 29
CSIE@NUTN Conditional Loops • Not know in advance how many times the loop would execute • Example – Continue prompting the user for a data value as long as the response is unreasonable. – Write this validating input loop in C with a while statement printf(“Enter number of observed values> “); scanf(“%d”, &num_obs); /* initialization */ while (num_obs < 0) { printf(“Negative number invalid; try again> “); scanf(“%d”, &num_obs); /* update */ } Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 30
Loop Design Sentinel-Controlled Loops CSIE@NUTN • Question – Many programs with loops input one or more additional data item is repeated – Often we don’t know how many data items the loop should process • Solution – Sentinel value • User to enter a unique data value • An end marker that follows the last item in a list of data Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 31
CSIE@NUTN Sentinel-Controlled Loops (Cont. ) • When the sentinel value is read – The loop repetition condition tests each item and cause loop exit – It could not normally occur as data • A loop that process data until the sentinel value is entered has the form 1. Get a line of data. 2. while the sentinel value has not been encountered 3. Process the data line. 4. Get another line of data. Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 32
CSIE@NUTN Sentinel-Controlled Loops (Cont. ) • Using a while statement Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 33
CSIE@NUTN Sentinel-Controlled Loops (Cont. ) • Using a for statement printf(”Eneter first score (or %d to quit)> “, SENTINEL); for (scanf(“%d”, &score); score != SENTINEL; scanf(“%d”, &score)) { sum += score ; printf(“Enter next score (%d to quit)> “, SENTINEL); } Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 34
CSIE@NUTN Endfile-Controlled Loops • Design a repetition statement very similar to the sentinel controlled loop • Use the state value returned – By the scanning function to control repetition • The pseudo code for an endfile-controlled loop 1. Get the first data value and save input status 2. while input status does not indicate that end of file has been reached 3. Process the data value 4. Get next data value and save input status Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 35
CSIE@NUTN Endfile-Controlled Loops (Cont. ) • scanf() returns the number of items of the argument list successfully filled. • What about the input is 7 a? – Infinite loop on faculty data !! • Correction while (input_status ==1) { ……. . } if (input_status ==EOF) printf(“the sum is” %d”, sum); else { scanf(inp, “%c”, &bad_char); printf(“Error input: %c”, bad_char); } Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 36
CSIE@NUTN Nested Loops • Nested loops consist of an outer loop with one or more inner loops • Each time the outer loop is repeated – The inner loops are reentered – Loop control expressions are reevaluated Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 37
Nested Loops (Cont. ) CSIE@NUTN • Example 5. 8 (Page 290) Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 38
Nested Loops (Cont. ) CSIE@NUTN • Example 5. 8 (Page 290) • Exercises : What is displayed by the following program segments, assuming m = 3 and n = 5 ? for (i = 1; i <= n; ++i) { for (j = 0; j < i; ++j) { printf(“*”); } printf(“n”); } Dr. Chow-Sing Lin output * ** ***** Repetition and Loop Statement - CH 5 39
CSIE@NUTN Nested Loops (Cont. ) for (i = n; i > 0; --i) { for (j = m; j > 0; --j) { printf(“*”); } printf(“n”); } output *** *** *** • Page 292: programming 1 and 2. Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 40
The do-while Statement and Flag-Controlled Loops CSIE@NUTN • Both the for statement and the while statement evaluate a loop repetition condition before the first execution of the loop body • We write the pseudo code for an input validation loop as follow : – 1. Get a data value – 2. If data value isn’t in the acceptable range • Go back to step 1 Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 41
The do-while Statement and Flag-Controlled Loops (Cont. ) CSIE@NUTN • SYNTAX do statement while (loop repetition condition); Example /* Find first even number input */ do status = scanf(“%d”, &num); while (status > 0 && (num % 2) != 0); Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 42
CSIE@NUTN Flag-controlled Loops • Flag – A type int variable (as boolean) – Represent whether or not a certain event has occurred • A flag has one of two values – 1 (true) – 0 (false) • Example 5. 10 (Page 294) Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 43
CSIE@NUTN Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 44
CSIE@NUTN Testing get_int(10, 20) Enter an integer in the range from 10 to 20 inclusive> @20 Invalid character >>@>>. Skipping rest of line. Enter an integer in the range from 10 to 20 inclusive> 2 o Number 2 is not in range. Enter an integer in the range from 10 to 20 inclusive> 20 Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 45
CSIE@NUTN Iterative Approximations • Find roots Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 46
CSIE@NUTN Change of Sign Implies an Odd Number of Roots Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 47
Three Possibilities That Arise When the Interval [Xleft, Xright] Is Bisected Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 CSIE@NUTN 48
CSIE@NUTN Figure 5. 19 Finding a Function Root using Bisection Method Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 49
CSIE@NUTN Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 50
CSIE@NUTN Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 51
CSIE@NUTN Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 52
Figure 5. 20 Sample Run of Bisection Program with Trace Code Included 1 -53
Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 54
Figure 5. 23 Program to draw a moving ball Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 55
Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 56
CSIE@NUTN How to Debug and Test Program • Using debugger – Existing in most popular IDE. (visual studio and Eclipse) • Without debugger – insert printf() to print system status whenever is necessary – Page. 294 • Off-by-one loop errors Dr. Chow-Sing Lin Repetition and Loop Statement - CH 5 57
CSIE@NUTN Common Programming Errors for (i=1; i<10; i++) ; { …. . } while( x>xbig) x-=2; ++xbig; // end of while Dr. Chow-Sing Lin while (balance != 0. 0) { } while (balance < 0. 0) { } do { ……. }while(again = 1) ; Repetition and Loop Statement - CH 5 58
- Slides: 58