Presentation is loading. Please wait.

Presentation is loading. Please wait.

Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin.

Similar presentations


Presentation on theme: "Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin."— Presentation transcript:

1 Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin

2 CSIE@NUTN Repetition Loop – The repetition of steps in a program Loop body – The statements that are repeated in the loop Dr. Chow-Sing Lin2Repetition and Loop Statement - CH 5

3 CSIE@NUTN Repetition (Cont.) Dr. Chow-Sing Lin3Repetition and Loop Statement - CH 5

4 CSIE@NUTN Loop Kinds KindWhen Used C Implementation Structures Counting loopWe can determine before loop execution exactly how many loop repetitions will be needed to solve the problem while for Sentinel-controlled loopInput of a list of data of any length ended by a special value while, for Endfile-controlled loopInput of a single list of data of any length from a data file while, for Input validation loopRepeated interactive input of a data value until a value within the valid range is entered do-while General conditional loopRepeated processing of data until a desired condition is met while, for Dr. Chow-Sing LinRepetition and Loop Statement - CH 54

5 CSIE@NUTN Counting Loop Counter-controlled loop (Counting loop) – A loop whose required number of iterations can be determined before loop execution begins Dr. Chow-Sing LinRepetition and Loop Statement - CH 55 Set loop control variable to an initial value of 0 while loop control variable < final value …… Increase loop control variable by 1

6 CSIE@NUTN while Statement SYNTAX Dr. Chow-Sing LinRepetition and Loop Statement - CH 56 while (loop repetition condition) statement /* Display N asterisks. */ count_star = 0; while (count_star < N) { printf(“*”); count_star = count_star + 1; } Example

7 CSIE@NUTN while Statement (Cont.) Computes and displays the gross pay for seven employees – Count_emp : loop control variable Dr. Chow-Sing LinRepetition and Loop Statement - CH 57 Loop repetition condition statement After seven weekly pay amounts are displayed

8 CSIE@NUTN while Statement (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 58

9 CSIE@NUTN Exercises Predict the output of this program fragment : Dr. Chow-Sing LinRepetition and Loop Statement - CH 59 i = 0; while (i <= 5) { printf(“%3d %3d\n”, i, 10 – i); i = i + 1; } output 0 10 19 28 37 465

10 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 LinRepetition and Loop Statement - CH 510

11 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 LinRepetition and Loop Statement - CH 511

12 CSIE@NUTN Computing a Sum in a Loop Dr. Chow-Sing LinRepetition and Loop Statement - CH 512 Accumulator : a variable used to store a value being computed in increments during the execution of a loop

13 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 LinRepetition and Loop Statement - CH 513

14 CSIE@NUTN Computing a Sum in a Loop (Cont.) Statementhoursratepaytotal_paycount_empEffect ???0.00 count_emp < number_emp true scanf (“%lf”, &hours); 50.0get hours scanf (“%lf”, &rate); 5.25get rate pay = hours * rate; 262.5find pay total_pay = total_pay + pay 262.5add to total_pay count_emp = count_emp +1 1Increment count_emp count_emp < number_emp true scanf (“%lf”, &hours); 6.0get hours scanf (“%lf”, &rate); 5.0get rate pay = hours * rate; 30.0find pay Dr. Chow-Sing LinRepetition and Loop Statement - CH 514

15 CSIE@NUTN Computing a Sum in a Loop (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 515 Statementhoursratepaytotal_paycount_empEffect total_pay = total_pay + pay 292.5add to total_pay count_emp = count_emp +1 2Increment count_emp count_emp < number_emp true scanf (“%lf”, &hours); 15.0get hours scanf (“%lf”, &rate); 7.0get rate pay = hours * rate; 105.0find pay total_pay = total_pay + pay 397.5add to total_pay count_emp = count_emp +1 3Increment count_emp

16 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 Dr. Chow-Sing LinRepetition and Loop Statement - CH 516 /* Multiply data while product remains less than 10000 */ product = 1; while (product “); scanf(“%d”, &item); product = product * item; /* Update product */ }

17 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 LinRepetition and Loop Statement - CH 517

18 CSIE@NUTN 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 LinRepetition and Loop Statement - CH 518

19 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 Dr. Chow-Sing LinRepetition and Loop Statement - CH 519 for (initialization expression; loop repetition condition; update expression) statement

20 CSIE@NUTN The for Statement (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 520 for (count_emp = 0 ;/* initialization */ count_emp < number_emp; /* loop repetition condition */ count_emp += 1) /* update */ Example /* Display N asterisks. */ for (count_star = 0; count_star < N; count_star += 1) printf (“*”); Example

21 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 is the value of the variable before it is incremented Dr. Chow-Sing LinRepetition and Loop Statement - CH 521

22 CSIE@NUTN Increment and Decrement Operator (Cont.) Given an initial value of 2 in i Dr. Chow-Sing LinRepetition and Loop Statement - CH 522

23 CSIE@NUTN Function to Compute Factorial Dr. Chow-Sing LinRepetition and Loop Statement - CH 523

24 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 LinRepetition and Loop Statement - CH 524

25 CSIE@NUTN Figure 5.8 Displaying a Celsius-to- Fahrenheit Conversion Table Dr. Chow-Sing LinRepetition and Loop Statement - CH 525

26 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 Dr. Chow-Sing LinRepetition and Loop Statement - CH 526 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);

27 CSIE@NUTN Review Question I (Cont.) StatementoddsumEffect sum = 0;0Initialize sum to 0 odd = 11Initialize odd to 1 odd < n;1 < 8 is true sum += odd;1sum = 0 + 1 odd += 23odd = 1 + 2 odd < n;3 < 8 is true sum += odd;4sum = 1 + 3 odd += 25odd = 3 + 2 odd < n;5 < 8 is true sum += odd;9sum = 4 + 5 odd += 27odd = 5 + 2 odd < n;7 < 8 is true Dr. Chow-Sing LinRepetition and Loop Statement - CH 527 For n = 8 :

28 CSIE@NUTN Review Question I (Cont.) StatementoddsumEffect sum += odd;16sum = 9 + 7 odd += 29odd = 7 + 2 odd < n;9 < 8 is false Exit loop printf (“Sum of…Output : Sum of positive odd numbers less than 8 is 16 Dr. Chow-Sing LinRepetition and Loop Statement - CH 528

29 CSIE@NUTN Review Question II Rewrite the code – No increment / decrement operator appears in an expression with another arithmetic operator Dr. Chow-Sing LinRepetition and Loop Statement - CH 529 ++i; --j; n = i * j; m = i + j; j--; p = i + j; n = ++i * --j; m = i + j--; p = i + j; Rewrite

30 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 Dr. Chow-Sing LinRepetition and Loop Statement - CH 530 printf(“Enter number of observed values> “); scanf(“%d”, &num_obs); /* initialization */ while (num_obs “); scanf(“%d”, &num_obs); /* update */ }

31 CSIE@NUTN Loop Design Sentinel-Controlled Loops 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 LinRepetition and Loop Statement - CH 531

32 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 Dr. Chow-Sing LinRepetition and Loop Statement - CH 532 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.

33 CSIE@NUTN Sentinel-Controlled Loops (Cont.) Using a while statement Dr. Chow-Sing LinRepetition and Loop Statement - CH 533

34 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 LinRepetition and Loop Statement - CH 534

35 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 Dr. Chow-Sing LinRepetition and Loop Statement - CH 535 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

36 CSIE@NUTN Endfile-Controlled Loops (Cont.) scanf() returns the number of items of the argument list successfully filled. What about the input is 7a? – 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 LinRepetition and Loop Statement - CH 536

37 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 LinRepetition and Loop Statement - CH 537

38 CSIE@NUTN Nested Loops (Cont.) Example 5.8 (Page 290) Dr. Chow-Sing LinRepetition and Loop Statement - CH 538

39 CSIE@NUTN Nested Loops (Cont.) Example 5.8 (Page 290) Exercises : What is displayed by the following program segments, assuming m = 3 and n = 5 ? Dr. Chow-Sing LinRepetition and Loop Statement - CH 539 for (i = 1; i <= n; ++i) { for (j = 0; j < i; ++j) { printf(“*”); } printf(“\n”); } * ** *** **** ***** output

40 CSIE@NUTN Nested Loops (Cont.) Dr. Chow-Sing LinRepetition and Loop Statement - CH 540 for (i = n; i > 0; --i) { for (j = m; j > 0; --j) { printf(“*”); } printf(“\n”); } *** output Page 292: programming 1 and 2.

41 CSIE@NUTN The do-while Statement and Flag-Controlled Loops 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 LinRepetition and Loop Statement - CH 541

42 CSIE@NUTN The do-while Statement and Flag-Controlled Loops (Cont.) SYNTAX Dr. Chow-Sing LinRepetition and Loop Statement - CH 542 do statement while (loop repetition condition); /* Find first even number input */ do status = scanf(“%d”, &num); while (status > 0 && (num % 2) != 0); Example

43 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 LinRepetition and Loop Statement - CH 543

44 CSIE@NUTN Dr. Chow-Sing LinRepetition and Loop Statement - CH 544

45 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> 2o Number 2 is not in range. Enter an integer in the range from 10 to 20 inclusive> 20 Dr. Chow-Sing LinRepetition and Loop Statement - CH 545

46 CSIE@NUTN Iterative Approximations Find roots Dr. Chow-Sing LinRepetition and Loop Statement - CH 546

47 CSIE@NUTN Change of Sign Implies an Odd Number of Roots Dr. Chow-Sing LinRepetition and Loop Statement - CH 547

48 CSIE@NUTN Three Possibilities That Arise When the Interval [X left, X right ] Is Bisected Dr. Chow-Sing LinRepetition and Loop Statement - CH 548

49 CSIE@NUTN Figure 5.19 Finding a Function Root using Bisection Method Dr. Chow-Sing LinRepetition and Loop Statement - CH 549

50 CSIE@NUTN Dr. Chow-Sing LinRepetition and Loop Statement - CH 550

51 CSIE@NUTN Dr. Chow-Sing LinRepetition and Loop Statement - CH 551

52 CSIE@NUTN Dr. Chow-Sing LinRepetition and Loop Statement - CH 552

53 Figure 5.20 Sample Run of Bisection Program with Trace Code Included 1-53

54 Dr. Chow-Sing LinRepetition and Loop Statement - CH 554

55 Figure 5.23 Program to draw a moving ball Dr. Chow-Sing LinRepetition and Loop Statement - CH 555

56 Dr. Chow-Sing LinRepetition and Loop Statement - CH 556

57 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 LinRepetition and Loop Statement - CH 557

58 CSIE@NUTN Common Programming Errors for (i=1; i<10; i++) ; { ….. } while( x>xbig) x-=2; ++xbig; // end of while Dr. Chow-Sing LinRepetition and Loop Statement - CH 558 while (balance != 0.0) { }  while (balance < 0.0) { } do { ……. }while(again = 1) ;


Download ppt "Problem Solving and Program Design in C Chap. 5 Repetition and Loop Statement Chow-Sing Lin."

Similar presentations


Ads by Google