Presentation is loading. Please wait.

Presentation is loading. Please wait.

A First Book of ANSI C Fourth Edition Chapter 5 Repetition.

Similar presentations


Presentation on theme: "A First Book of ANSI C Fourth Edition Chapter 5 Repetition."— Presentation transcript:

1 A First Book of ANSI C Fourth Edition Chapter 5 Repetition

2 A First Book of ANSI C, Fourth Edition2 Objectives Basic Loop Structures The while Statement Computing Sums and Averages Using a while Loop The for Statement

3 A First Book of ANSI C, Fourth Edition3 The programs examined so far have been in illustrating the correct structure of C programs and in introducing fundamental C input, assignment, and selection capabilities. The real power of most computer programs is their ability to repeat the same calculation of sequence of instructions many times, each time using different data, without rerunning the program for each new set of data values. In this chapter we explore the C statements that permit this. These statements are the while, for, and do-while statements.

4 A First Book of ANSI C, Fourth Edition4 Objectives (continued) Case Studies: Loop Programming Techniques Nested Loops The do-while Statement Common Programming and Compiler Errors

5 A First Book of ANSI C, Fourth Edition5 Introduction A section of code that is repeated is called a loop, because after the last statement in the code is executed, the program branches, or loops, back to the first statement and starts another repetition through the code Each repetition is also called an iteration or pass through the loop

6 A First Book of ANSI C, Fourth Edition6 5.1 Basic Loop Structures Constructing a repeating section of code requires that four elements be present: –Repetition statement while statement for statement do-while statement –Condition –A statement that initially sets the condition being tested –A statement within the repeating section of code that alters the condition so that it eventually becomes false

7 A First Book of ANSI C, Fourth Edition7 Pretest and Posttest Loops

8 A First Book of ANSI C, Fourth Edition8 Pretest and Posttest Loops (continued)

9 A First Book of ANSI C, Fourth Edition9 Counter-Controlled and Condition-Controlled Loops Counter-controlled loop: the condition is used to keep track of the number of repetitions –Also known as a fixed-count loop Condition-controlled loop: the tested condition does not depend on a count being achieved, but rather on a specific value being encountered

10 A First Book of ANSI C, Fourth Edition10 Basic Loop Structures

11 A First Book of ANSI C, Fourth Edition11 5.2 The while Statement The while statement is a general repetition statement that can be used in a variety of programming situations. The form of the while statement is while (expression) statement ;

12 A First Book of ANSI C, Fourth Edition12 The while Statement The transfer of control back to the start of a while statement to reevaluate the expression is known as a program loop The following is a valid but infinite loop: while (count <= 10) printf("%d ",count);

13 A First Book of ANSI C, Fourth Edition13 The while Statement (continued)

14 A First Book of ANSI C, Fourth Edition14 Program 5.1 # include int main () { int count; count = 1; /* initialize count*/ while (count <=10) { printf (“%d “, count); ++count; /* add 1 to count */ } return 0; }

15 A First Book of ANSI C, Fourth Edition15 The while Statement (continued) Output is: 1 2 3 4 5 6 7 8 9 10

16 A First Book of ANSI C, Fourth Edition16 Before we consider other example of the while statement, two comments concerning Program 5.1 are in order. First, the statement ++count can be replaced with any statement that can change the value of count. A statement such as count = count + 2, for example, would cause every second integer to be displayed. Second, it is the programmer “s responsibility to ensure that count is changed in a way that ultimately leads to a normal exit from the while.

17 A First Book of ANSI C, Fourth Edition17 Now that you have some familiarity with the while statements, see if you can read and determine the output of Program 5.2.

18 A First Book of ANSI C, Fourth Edition18 Program 5.2 # include { int i; i = 10; while (i >== 1) { printf (“%d ”, i); --i; /* subtract 1 form i */ } return 0; }

19 A First Book of ANSI C, Fourth Edition19 The while Statement (continued) Output is: 10 9 8 7 6 5 4 3 2 1

20 A First Book of ANSI C, Fourth Edition20 The assignment statement in Program 5.2 initially sets variable i to 10. The while statement then checks to see if the value of i is greater than or equal to 1. While the expression is true, the value of i is displayed by the call to printf () and the value of i is decremented by 1. When i finally reaches zero, the expression is false and program exists the while statement.

21 A First Book of ANSI C, Fourth Edition21 To illustrate the power of the while statement, consider the task of printing a table of number from 1 to 10 with their squares and cubs. This can be done with a simple while statement, as illustrated by Program 5.3

22 A First Book of ANSI C, Fourth Edition22 Program 5.3 # include int main () { int num; printf (“NUMBER SQUARE CUBE\n”); printf (“----- ----- ---- \n”); num = 1; while (num < 11) { printf (“%3d %3d %4d\n, num, num*num, num*num*num); ++num; /* add 1 to num*/ } return 0; }

23 A First Book of ANSI C, Fourth Edition23 Program 5.3 produces the following display. NUMBER SQUARE CUBE ----- ----- ---- 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000

24 A First Book of ANSI C, Fourth Edition24 Note that the expression used in Program 5.3 is num< 11. For the integer variable num, this expression is exactly equivalent to the expression num<= 10. The choice of which to use is entirely up to you.

25 A First Book of ANSI C, Fourth Edition25 If you want to use Program 5.3 to produce a table of 1000 numbers, all you do is change the expression in the while statement from i<11 to i <1001. Changing the 11 to 1001 produces a table of 1000 line-not bad for a simple five-line while statement.

26 A First Book of ANSI C, Fourth Edition26 The while Statement (continued) Output is: NUMBER SQUARE CUBE ------ ------ ---- 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000

27 A First Book of ANSI C, Fourth Edition27 As before, the while statement consists of everything from the word while through the closing brace of the compound statement. Prior to the while loop we have made sure to assign a value to the operand being evaluated, and there is a statement to alter the value of Celsius to ensure an exit from the while loop. Program 5.4 illustrates the use of code in a complete program.

28 A First Book of ANSI C, Fourth Edition28.Program 5.4 # include int main() /* program to convert Celsius to Fahrenheit */ { int celsius; float fahren; printf (“ DEGREES DEGREES\n”); printf (“CELSIUS FAHRENHEIT\n”); printf (“------------ ------------------\n”);

29 A First Book of ANSI C, Fourth Edition29 Celsius = 5; /* starting Celsius value */ while (Celsius <= 50) { fahrenn = (9.0/5.0) * celsius +32.0; printf (“%5d%12.2f\n”. celsius, fahren);; celsius = celsius + 5; } return 0; }

30 A First Book of ANSI C, Fourth Edition30 The display obtained when program 5.4 is executed is DEGREES DEGREES CELSIUS FAHRENHEIT ----------- ------------------ 5 41.00 10 50.00 15 59.00 20 68.00 25 77.00 30 86.00 35 95.00 40 104.00 45 113.00 50 122.00

31 A First Book of ANSI C, Fourth Edition31 Condition-controlled loop Output is: DEGREES CELSIUS FAHRENHEIT ------- ---------- 5 41.00 10 50.00 15 59.00 20 68.00 25 77.00 30 86.00 35 95.00 40 104.00 45 113.00 50 122.00 The while Statement (continued)

32 A First Book of ANSI C, Fourth Edition32 5.3 Computing Sums and Averages within a while loop Combining the scanf () function with the repetition capabilities of the while statement produces very adaptable and powerful programs. To understand the concept involved, Consider Program 5.5, where a while statement is used to accept and then display four user-entered numbers, one at a time.

33 A First Book of ANSI C, Fourth Edition33 Program 5.5 # include int main () { int count ; float num; printf (“\n This is program will ask you to enter some number.\n”);

34 A First Book of ANSI C, Fourth Edition34 count = 1; while (count <= 4) { printf (“\n Enter a number : “); scanf (“%f”, &num); printf (“The number entered is %f”, num); ++count; } return 0; }

35 A First Book of ANSI C, Fourth Edition35 Computing Sums and Averages Using a while Loop

36 A First Book of ANSI C, Fourth Edition36 Computing Sums and Averages Using a while Loop (continued)

37 A First Book of ANSI C, Fourth Edition37 Once the while loop is entered, the statements within the compound statement are executed while the tested condition is true. The first time through the compound statement, the message Enter a number: is displayed. The program then calls the scanf (), which forces the computer to wait for a number to be entered at the keyboard.

38 A First Book of ANSI C, Fourth Edition38 Once a number is typed and the ENTER key is pressed, the call to printf () displaying the number is executed. The variable count is then incremented by one. This process continues until four passes through the loop have been made and the value of count is 5. Each pass causes the message Enter a number: to be displayed, causes one call to scanf () to be made, and causes the message The number entered is to be displayed.

39 A First Book of ANSI C, Fourth Edition39 Rather than simply displaying the entered numbers, Program 5.5 can be modified to use the entered data. For example, we can add the numbers entered and display the total. To do this, we must be very careful in how we add the numbers, since the same variable, num, is used for each number entered.

40 A First Book of ANSI C, Fourth Edition40 Because of this the entry of a new number in Program 5.5 automatically causes the previous number stored in num to be lost. Thus, each number entered must be added to the total before another number is entered. The required sequence is Enter a number Add the number to the total How do we add a number to a total?

41 A First Book of ANSI C, Fourth Edition41 A statement such as total =total+ num; does the job perfect. This is the accumulating statement introduced in section 3.1. After each number is entered, the accumulating statement adds the number into the total, as illustrated in Figure 5.5.

42 A First Book of ANSI C, Fourth Edition42 Computing Sums and Averages Using a while Loop (continued)

43 A First Book of ANSI C, Fourth Edition43 Computing Sums and Averages Using a while Loop (continued)

44 A First Book of ANSI C, Fourth Edition44 Program 5.6 # include Int main ( ) { int count; float num, total; printf (“\n This program will ask you to enter some number.\n”); count = 1; total = 0;

45 A First Book of ANSI C, Fourth Edition45 while (count <= 4) { printf (“\n Enter a number : “); scanf (“%f”, sum); total = total+ num; printf (“The total is now %f”, total); ++count; } printf (“\n\n The final total is %f”, total); return 0; )

46 A First Book of ANSI C, Fourth Edition46 Let us review program 5.6. The variable total was created to store the total of the number entered. Prior to entering the while statement the value of total is set to zero. This ensures that any previous value present in the storage location assigned to the variable total is overwritten. When the while loop is entered, the statement total = total+ num is used to add the value of the entered number into total.

47 A First Book of ANSI C, Fourth Edition47 Ensures that any previous value present in the storage locations assigned to the variable total is overwritten and the total starts at a correct value Accumulating statement Computing Sums and Averages Using a while Loop (continued)

48 A First Book of ANSI C, Fourth Edition48 Having used an accumulating assignment to add the number entered, we can now go further and calculate the average of the number. Where do we calculate the average— within the while loop or outside it?

49 A First Book of ANSI C, Fourth Edition49 In the case at hand, calculating an average requires that both a final sum and the number of items in that sum be available. The average is then computed by dividing the final sum by the number of items. At this point, we must ask, “At what point in the program is the correct sum available, and at what point is the number of items available?” In reviewing Program 5.6 we see that the correct sum needed for calculating the average is available after the while loop is finished.

50 A First Book of ANSI C, Fourth Edition50 In fact, the whole purpose of the while loop is to ensure that the numbers are entered and added correctly to produce a correct sum. Within this as background, see if you can read and understand Program 5.7

51 A First Book of ANSI C, Fourth Edition51 Program 5.7 # include int main () { int count; float num, total,average; printf (“\n This program will ask you to enter some numbers.\n”); count = 1; total = 0;

52 A First Book of ANSI C, Fourth Edition52 while (count <=4) { printf (“Enter a number : “); scanf (“%f”, &num); total = total + num; ++count; } --count; average = total /count; printf (“\n The average of the numbers is %f”, average); return 0; }

53 A First Book of ANSI C, Fourth Edition53 Following is sample run using Program5.7. This program will ask you to enter some numbers. Enter a number: 26.2 Enter a number: 5 Enter a number: 103.456 Enter a number: 1267.89 The average of the number is 350.636500

54 A First Book of ANSI C, Fourth Edition54 Calculating an average Computing Sums and Averages Using a while Loop (continued)

55 A First Book of ANSI C, Fourth Edition55 Sentinels A program, such as Program 5.7, can be made much more general by removing the restriction that exactly four numbers are to be entered –The user enters a value for how many numbers will be averaged –You can use a sentinel (a data value used to signal either the start or end of a data series) The sentinel values must be selected so as not to conflict with legitimate data values

56 A First Book of ANSI C, Fourth Edition56 Program 5.8 # include int main () { float grade, total; grade = 0; total = 0; printf (“\n To stop entering grade, type in any number”) printf (“\n grater than 100.\n\n”);

57 A First Book of ANSI C, Fourth Edition57 while (grade <= 100) { printf (“Enter a grade: “); scanf (“%f, &grade); total = total + grade; } printf (“\n The total of the grade is %f”, total - grade); return 0; }

58 A First Book of ANSI C, Fourth Edition58 Following is a sample run using program 5.8. As long as grades less than 100 are entered, the program continues to request and accept additional data. When a number greater than 100 is entered, the program adds this number to the total and exits the while loop. Outside of the loop and within the printf () function call, the value of the sentinel that was added to the total is subtracted and the sum of the legitimate grades that were entered is displayed.

59 A First Book of ANSI C, Fourth Edition59 To stop entering grade, type in any number greater than 100. Enter a grade: 95 Enter a grade: 100 Enter a grade: 82 Enter a grade: 101 The total of the grades is 277.000000

60 A First Book of ANSI C, Fourth Edition60 Sentinels (continued)

61 A First Book of ANSI C, Fourth Edition61 Sentinels (continued) One useful sentinel in C is the named constant EOF (End Of File) –The actual value of EOF is compiler- dependent, but it is always assigned a code that is not used by any other character –EOF is defined in stdio.h

62 A First Book of ANSI C, Fourth Edition62 Sentinels (continued)

63 A First Book of ANSI C, Fourth Edition63 Program 5.9 # include int main() { float grade, total = 0; /* note the initialization here*/ printf (“\n To stop entering grades, press either the F6 key”); printf (“\n or the ctrl and z keys simultaneous on IBM computers”); printf (“\n or the ctrl and D keys for UNIX operating systems.\n\n”);

64 A First Book of ANSI C, Fourth Edition64 printf (“Enter a grade: “); while (scanf (“%f”, &grade) != EOF) { total = total + grade; printf (“Enter a grade : “); } printf (“\n The total of the grades is %f”, total); return 0; }

65 A First Book of ANSI C, Fourth Edition65 To stop entering grades, press either the F6 key or the ctrl and Z keys simultaneously on IBM computers or the ctrl and D keys for UNIX operating systems Enter a grade: 100 Enter a grade: 200 Enter a grade: 300 Enter a grade: ^Z The total of the grades is 600.000000

66 A First Book of ANSI C, Fourth Edition66 Sentinels (continued)

67 A First Book of ANSI C, Fourth Edition67 The break and continue Statements A break forces an immediate exit from while, switch, for, and do-while statements only while(count <= 10) { printf("Enter a number: "); scanf("%f", &num); if (num > 76) { printf("You lose!"); break; /* break out of the loop */ } else printf("Keep on truckin!"); } /* break jumps to here */

68 A First Book of ANSI C, Fourth Edition68 The continue applies to loops only; when a continue statement is encountered in a loop, the next iteration of the loop begins immediately while (count < 30) { printf("Enter a grade: "); scanf("%f", &grade); if(grade 100) continue; total = total + grade; count = count + 1; }

69 A First Book of ANSI C, Fourth Edition69 The Null Statement A semicolon with nothing preceding it is also a valid statement, called the null statement ; Use the null statement where a statement is syntactically required, but no action is needed Null statements typically are used either with while or for statements

70 A First Book of ANSI C, Fourth Edition70 The for Statement The for statement combines all four elements required to easily produce a loop on the same line for (initializing list; tested expression; altering list) statement; This statement does not require that any of the items in parentheses be present or that they actually be used for initializing or altering the values in the expression statements –However, the two semicolons must be present for ( ; count <= 20;) is valid Omitting tested expression results in infinite loop

71 A First Book of ANSI C, Fourth Edition71 The for Statement (continued)

72 A First Book of ANSI C, Fourth Edition72 Program 5.10 # include int main () { int count; for (count = 2; count <= 20; count = count +2) printf (“%d “, count); return 0; }

73 A First Book of ANSI C, Fourth Edition73 The for Statement (continued) Output is: 2 4 6 8 10 12 14 16 18 20

74 A First Book of ANSI C, Fourth Edition74 Program 5.10a # include int main () { int count; count = 2; /* initialize outside for statement */ for ( ; count <= 20; count = count +2); printf (“%d “,count); return 0; }

75 A First Book of ANSI C, Fourth Edition75 Program 5.10b # include int main () { int count; count = 2; /*; initialize outside for statement */ for ( ; count <= 20; ) { printf (“%d “, count); count = count + 2; /* alteration statement */ } return 0; }

76 A First Book of ANSI C, Fourth Edition76 Program 5.10c # include int main() /* all expression within the for’s parentheses */ { int count; for (count =2; count <= 20; printf (“%d “, count), count = count +2); return 0; }

77 A First Book of ANSI C, Fourth Edition77 The for Statement (continued)

78 A First Book of ANSI C, Fourth Edition78 The for Statement (continued)

79 A First Book of ANSI C, Fourth Edition79 The for Statement (continued) Comma-separated list

80 A First Book of ANSI C, Fourth Edition80 To understand the enormous power of the for statement, consider the task of printing a table of numbers from 1 to 10, including their squares and cubes, using this statement. Such a table was previously produced using a while statement in program 5.3. You may wish to review program 5.3 and compare it to program 5.11 to get a further sense of the equivalent between the for and while statements.

81 A First Book of ANSI C, Fourth Edition81 Program 5.11 # include int main () { int num; printf (“NUMBER SQUARE CUBE\n”); printf (“------------ ----------- ------\n”); for (num = 1; num <= 10; ++num) printf (“%3d %3d %3d\n”, num, num*num, mum*num*num); return 0; }

82 A First Book of ANSI C, Fourth Edition82 Program 5.11 produces the following display: NUMBER SQUARE CUBE ------------ ----------- ------- 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000

83 A First Book of ANSI C, Fourth Edition83 The for Statement (continued) (compare with Program 5.3)

84 A First Book of ANSI C, Fourth Edition84 Simple change 10 in the for statement of program 5.11 to 1000 creates a loop that is executed 1000 times and produces a table of a numbers from 1 to 1000. As with the while statement this small change produces an immense increase in the processing and output provided by the program.

85 A First Book of ANSI C, Fourth Edition85 scanf () within a for Loop Using a scanf () function call inside a for loop produces the same effect as when this function is called inside a while loop. For example, in program 5.12 a scanf () function call is used to input a set of numbers. As each number is input, it is added to a total. When the for loop is exited, the average is calculated and displayed..

86 A First Book of ANSI C, Fourth Edition86 Program 5.12 # include int main() /* This program calculates the average */ /* of five user-entered number. */ { int count; float num, total, average; total = 0.0;

87 A First Book of ANSI C, Fourth Edition87 for (count = 0; count <5; ++count) { printf (“\n Enter a number :”); scanf (“%f”, &num); total = total + num; } average = total / count; printf (“\n\n The average of the data entered is %f”, average); return 0; }

88 A First Book of ANSI C, Fourth Edition88 Although, for clarity, total was initialized to zero before the for statement, this initialization could have been included with the initialization of count, as follows: for (total =0.0, count = 0; count < 5; ++count)

89 A First Book of ANSI C, Fourth Edition89 Computing Sums and Averages Using a for Loop

90 A First Book of ANSI C, Fourth Edition90 5.5 Case Studies: Loop Programming Techniques Technique 1: Selection within a loop Technique 2: Input data validation Technique 3: Interactive loop control Technique 4: Evaluating equations

91 A First Book of ANSI C, Fourth Edition91 Technique 1: Selection within a Loop

92 A First Book of ANSI C, Fourth Edition92 Technique 2: Input Data Validation Same code used in lines 6-7!

93 A First Book of ANSI C, Fourth Edition93 Technique 2: Input Data Validation (continued)

94 A First Book of ANSI C, Fourth Edition94 Technique 3: Interactive Loop Control

95 A First Book of ANSI C, Fourth Edition95 Technique 4: Evaluating Equations

96 A First Book of ANSI C, Fourth Edition96 Technique 4: Evaluating Equations (continued)

97 A First Book of ANSI C, Fourth Edition97 Nested Loops There are many situations in which it is very convenient to have a loop contained within another loop. Such loops are called nested loops.

98 A First Book of ANSI C, Fourth Edition98 A simple example is for ( i = 1; i <= 5; ++i) /* start of outer loop  + */ { /* ︳ */ printf (“\n i is now %d\n”, i) /* ︳ */ for (j = 1; j <= 4; ++j) /* start of inner loop*/ printf (“ j = %d”, j); /* end of inner loop ︳ */ } /* end of outer loop  --+ */

99 A First Book of ANSI C, Fourth Edition99 The first loop, controlled by the value of i is called the outer loop. The second loop, controlled by the value of j, is called the inner loop. Notice that all statements in the inner loop are contained within the boundaries of the outer loop and that we have used a different variable to control each loop.

100 A First Book of ANSI C, Fourth Edition100 For each single trip through the outer loop, the inner loop runs through its entire sequence. Thus, each time the i counter increases by 1, the inner for loop executes completely. This situation is illustrated in figure 5.9. Program 5.19 includes the above code in a working program.

101 A First Book of ANSI C, Fourth Edition101 Proram 5.19 # include int main () { int i, j; for (i = 1; i <= 5; ++i) /* start of outer loop  ----+*/ { /* ︳ */ printf (“\n i is now d\n”, i ) /* ︳ */ for (j = 1; j <= 4; ++j) /* start of inner loop ︳ */ printf (“ j = %d”, j); /* end of inner loop ︳ */ } /* end of outer loop ︳ */ return 0; }

102 A First Book of ANSI C, Fourth Edition102 Following is output of a simple run of program 5.19. i is now 1 j = 1 j = 2 j =3 j = 4 i is now 2 j =1 j = 2 j =3 j = 4 i is now 3 j =1 j = 2 j =3 j = 4 i is now 4 j =1 j = 2 j =3 j = 4

103 A First Book of ANSI C, Fourth Edition103 Let us use a nested loop to compute the average grade for each student in a class of 20. Each student has taken four exams during the course of the semester. The final grade is calculated as the average of these examination grades.

104 A First Book of ANSI C, Fourth Edition104 Program 5.20 # include int main() { int i, j; float grade, total, average; for (i = 1; i <= 20; ++i) { total = 0; for (j = 1; j <= 4; ++j) {printf (“Enter an examination grade for this student : “); scanf(“%f”,&grade), total = total +grade; } average = total / 4; printf (“\n The average for student %d is %f \n\n”, i, average); } return 0; }

105 A First Book of ANSI C, Fourth Edition105 In reviewing program 5.20, pay particular attention to the initialization of total within the outer loop before the inner loop is entered. The variable total is initialized 20 times, once for each student. Also notice that average is calculated and displayed immediately after the inner loop is finished.

106 A First Book of ANSI C, Fourth Edition106 5.7 The do-while Statement Both the while and the for statements evaluate an expression at the start of the repetition loop. There are cases, however, where it is more convenient to test the expression at the end of the loop.

107 A First Book of ANSI C, Fourth Edition107 The do statement, as its name implies, allows us to do some statements before an expression is evaluated. The general form of the do statement is do statement; while (expression);  ---don’t forget the final;

108 A First Book of ANSI C, Fourth Edition108 As with all C programs, the single statement in the do may be replaced with a compound statement. A flow-control diagram illustrating the operation of the do statement is shown in figure 5.10

109 A First Book of ANSI C, Fourth Edition109 As illustrated in Figure 5.10, all statements within the do statement are executed at least once before the expression is evaluated. Then, if the expression has nonzero value, the statements are executed again. This process continues until the expression evaluates to zero. For example, consider the following do statement:

110 A First Book of ANSI C, Fourth Edition110 do { printf (“\n Enter a price : “); scanf (“”%f”, &price); if (price < SENTINEL) break; salestax = RATE * price; printf(“ The sales tax is $%5.2f”, salestax); } while (price != SENTINEL);

111 A First Book of ANSI C, Fourth Edition111 Here the compound statement within the loop will always be executed at least once, regardless of the value of the tested condition. They will then be repeatedly executed as long as the condition remains true. Notice that in this section of code the loop is also stopped when the sentinel value is encountered.

112 A First Book of ANSI C, Fourth Edition112 As with all repetition statements, the do statement can always replace or be replaced by an equivalent while or for statement. The choice of which statements to use depends on the application and the style preferred by the programmer. In general, the while and for statements are preferred because they clearly let anyone reading the program know what is being tested “right up front” at the top of the program loop.

113 A First Book of ANSI C, Fourth Edition113 Validity Checks The do statement is particularly useful in filtering user-entered input and providing data validity checks. For example, assume that an operator is required to enter a valid customer identification number between the numbers 1000 and 1999. A number outside this range is to be rejected, and a new request for a valid number made. The following section of code provides the necessary data filter to verify the entry of a valid identification number:

114 A First Book of ANSI C, Fourth Edition114 do { printf (“%\n Enter an identification number: “); scanf (“%f”, &idNum); } whilie (idNum 1999);

115 A First Book of ANSI C, Fourth Edition115 Here, a request for an identification number is repeated until a valid number is entered. This section of code is “bare bones” in that it neither alters the operator to the cause of the new request for data nor allows premature exit from the loop if a valid identification number cannot be found. An alternative for removing the first drawback is

116 A First Book of ANSI C, Fourth Edition116 do { prntf (“\n Enter an identification number : “); scanf (“%f”. &idNum); if (idNum 1999) { printf (“\n An invalid number was just entered”); printf (“\n please check the ID number and re-enter”); } else break; /* break if a valid id num was entered */ } while (1); /* this expression is always true*/

117 A First Book of ANSI C, Fourth Edition117 Here we have used a break statement to exit the loop. Because the expression being evaluated by the do statement is always 1 (true), an infinite loop has been created that is exited only when the break statement is encountered.


Download ppt "A First Book of ANSI C Fourth Edition Chapter 5 Repetition."

Similar presentations


Ads by Google