Top Banner
A First Book of ANSI C Fourth Edition Chapter 5 Repetition
117
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: A First Book of ANSI C Fourth Edition Chapter 5 Repetition.

A First Book of ANSI CFourth Edition

Chapter 5Repetition

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

A First Book of ANSI C, Fourth Edition 2

Objectives

• Basic Loop Structures

• The while Statement

• Computing Sums and Averages Using a while Loop

• The for Statement

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

A First Book of ANSI C, Fourth Edition 3

• 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.

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

A First Book of ANSI C, Fourth Edition 4

Objectives (continued)

• Case Studies: Loop Programming Techniques

• Nested Loops

• The do-while Statement

• Common Programming and Compiler Errors

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

A First Book of ANSI C, Fourth Edition 5

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

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

A First Book of ANSI C, Fourth Edition 6

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

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

A First Book of ANSI C, Fourth Edition 7

Pretest and Posttest Loops

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

A First Book of ANSI C, Fourth Edition 8

Pretest and Posttest Loops (continued)

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

A First Book of ANSI C, Fourth Edition 9

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

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

A First Book of ANSI C, Fourth Edition 10

Basic Loop Structures

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

A First Book of ANSI C, Fourth Edition 11

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;

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

A First Book of ANSI C, Fourth Edition 12

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);

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

A First Book of ANSI C, Fourth Edition 13

The while Statement (continued)

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

A First Book of ANSI C, Fourth Edition 14

• Program 5.1• # include <stdio.h>• int main ()• {• int count;• count = 1; /* initialize count*/• while (count <=10)• {• printf (“%d “, count);• ++count; /* add 1 to count */• }• return 0;• }

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

A First Book of ANSI C, Fourth Edition 15

The while Statement (continued)

Output is:1 2 3 4 5 6 7 8 9 10

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

A First Book of ANSI C, Fourth Edition 16

• 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.

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

A First Book of ANSI C, Fourth Edition 17

• Now that you have some familiarity with the while statements, see if you can read and determine the output of Program 5.2.

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

A First Book of ANSI C, Fourth Edition 18

• Program 5.2• # include <stdio.h>• {• int i;• i = 10;• while (i >== 1)• {• printf (“%d ”, i);• --i; /* subtract 1 form i */• }• return 0;• }

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

A First Book of ANSI C, Fourth Edition 19

The while Statement (continued)

Output is:10 9 8 7 6 5 4 3 2 1

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

A First Book of ANSI C, Fourth Edition 20

• 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.

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

A First Book of ANSI C, Fourth Edition 21

• 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

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

A First Book of ANSI C, Fourth Edition 22

• Program 5.3

• # include <stdio.h>• 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;• }

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

A First Book of ANSI C, Fourth Edition 23

• 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

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

A First Book of ANSI C, Fourth Edition 24

• 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.

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

A First Book of ANSI C, Fourth Edition 25

• 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.

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

A First Book of ANSI C, Fourth Edition 26

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

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

A First Book of ANSI C, Fourth Edition 27

• 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.

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

A First Book of ANSI C, Fourth Edition 28

• .Program 5.4

• # include <stdio.h>

• int main() /* program to convert Celsius to Fahrenheit */

• {

• int celsius;

• float fahren;

• printf (“ DEGREES DEGREES\n”);

• printf (“CELSIUS FAHRENHEIT\n”);

• printf (“------------ ------------------\n”);

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

A First Book of ANSI C, Fourth Edition 29

• 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;• }

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

A First Book of ANSI C, Fourth Edition 30

• 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

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

A First Book of ANSI C, Fourth Edition 31

Condition-controlled loop

Output is:DEGREES DEGREESCELSIUS 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)

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

A First Book of ANSI C, Fourth Edition 32

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.

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

A First Book of ANSI C, Fourth Edition 33

• Program 5.5

• # include <stdio,h>

• int main ()

• {

• int count ;

• float num;

• printf (“\n This is program will ask you to enter some number.\n”);

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

A First Book of ANSI C, Fourth Edition 34

• count = 1;• while (count <= 4)• {• printf (“\n Enter a number : “);• scanf (“%f”, &num);• printf (“The number entered is %f”, num);• ++count;• }• return 0;• }

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

A First Book of ANSI C, Fourth Edition 35

Computing Sums and Averages Using a while Loop

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

A First Book of ANSI C, Fourth Edition 36

Computing Sums and Averages Using a while Loop (continued)

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

A First Book of ANSI C, Fourth Edition 37

• 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.

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

A First Book of ANSI C, Fourth Edition 38

• 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.

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

A First Book of ANSI C, Fourth Edition 39

• 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.

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

A First Book of ANSI C, Fourth Edition 40

• 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?•

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

A First Book of ANSI C, Fourth Edition 41

• 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.

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

A First Book of ANSI C, Fourth Edition 42

Computing Sums and Averages Using a while Loop (continued)

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

A First Book of ANSI C, Fourth Edition 43

Computing Sums and Averages Using a while Loop (continued)

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

A First Book of ANSI C, Fourth Edition 44

• Program 5.6

• # include <stdio.h> • Int main ( ) • {• int count;• float num, total;• printf (“\n This program will ask you to enter some

number.\n”);• count = 1;• total = 0;

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

A First Book of ANSI C, Fourth Edition 45

• 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;• )

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

A First Book of ANSI C, Fourth Edition 46

• 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.

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

A First Book of ANSI C, Fourth Edition 47

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)

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

A First Book of ANSI C, Fourth Edition 48

• 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?

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

A First Book of ANSI C, Fourth Edition 49

• 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.

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

A First Book of ANSI C, Fourth Edition 50

• 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

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

A First Book of ANSI C, Fourth Edition 51

• Program 5.7• # include <stdio.h>• int main ()• {• int count;• float num, total ,average;• printf (“\n This program will ask you to

enter some numbers.\n”);• count = 1;• total = 0;

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

A First Book of ANSI C, Fourth Edition 52

• 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;• }

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

A First Book of ANSI C, Fourth Edition 53

• 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

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

A First Book of ANSI C, Fourth Edition 54

Calculating an average

Computing Sums and Averages Using a while Loop (continued)

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

A First Book of ANSI C, Fourth Edition 55

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

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

A First Book of ANSI C, Fourth Edition 56

• Program 5.8

• # include <stdio.h>• 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”);

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

A First Book of ANSI C, Fourth Edition 57

• 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;• }

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

A First Book of ANSI C, Fourth Edition 58

• 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.

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

A First Book of ANSI C, Fourth Edition 59

• 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

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

A First Book of ANSI C, Fourth Edition 60

Sentinels (continued)

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

A First Book of ANSI C, Fourth Edition 61

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

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

A First Book of ANSI C, Fourth Edition 62

Sentinels (continued)

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

A First Book of ANSI C, Fourth Edition 63

• Program 5.9

• # include <stdio.h>• 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”);

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

A First Book of ANSI C, Fourth Edition 64

• 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;• }

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

A First Book of ANSI C, Fourth Edition 65

• 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

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

A First Book of ANSI C, Fourth Edition 66

Sentinels (continued)

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

A First Book of ANSI C, Fourth Edition 67

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 */

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

A First Book of ANSI C, Fourth Edition 68

• 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 < 0 || grade > 100) continue; total = total + grade; count = count + 1;}

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

A First Book of ANSI C, Fourth Edition 69

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

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

A First Book of ANSI C, Fourth Edition 70

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

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

A First Book of ANSI C, Fourth Edition 71

The for Statement (continued)

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

A First Book of ANSI C, Fourth Edition 72

• Program 5.10

• # include <stdio.h>

• int main ()• {

• int count;

for (count = 2; count <= 20; count = count +2)

• printf (“%d “, count);

• return 0;

• }

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

A First Book of ANSI C, Fourth Edition 73

The for Statement (continued)

• Output is:2 4 6 8 10 12 14 16 18 20

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

A First Book of ANSI C, Fourth Edition 74

• Program 5.10a

• # include <stdio.h>• int main ()• {• int count;• count = 2; /* initialize outside for

statement */• for ( ; count <= 20; count = count +2);• printf (“%d “,count);• return 0;• }

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

A First Book of ANSI C, Fourth Edition 75

• Program 5.10b

• # include <stdio.h>• int main ()• {• int count;• count = 2; /*; initialize outside for statement */• for ( ; count <= 20; )• {• printf (“%d “, count);• count = count + 2; /* alteration statement */• }• return 0;• }

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

A First Book of ANSI C, Fourth Edition 76

• Program 5.10c

• # include <stdio.h>• int main() /* all expression within the for’s

parentheses */• {• int count;• for (count =2; count <= 20; printf (“%d “, count),

count = count +2);• return 0;• }

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

A First Book of ANSI C, Fourth Edition 77

The for Statement (continued)

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

A First Book of ANSI C, Fourth Edition 78

The for Statement (continued)

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

A First Book of ANSI C, Fourth Edition 79

The for Statement (continued)

Comma-separated list

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

A First Book of ANSI C, Fourth Edition 80

• 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.

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

A First Book of ANSI C, Fourth Edition 81

• Program 5.11

• # include <stdio.h>• 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;• }

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

A First Book of ANSI C, Fourth Edition 82

• 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

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

A First Book of ANSI C, Fourth Edition 83

The for Statement (continued)

(compare with Program 5.3)

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

A First Book of ANSI C, Fourth Edition 84

• 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.

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

A First Book of ANSI C, Fourth Edition 85

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..

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

A First Book of ANSI C, Fourth Edition 86

• Program 5.12

• # include < stio.h>• int main()• /* This program calculates the average */• /* of five user-entered number. */• {• int count;• float num, total, average;• total = 0.0;•

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

A First Book of ANSI C, Fourth Edition 87

• 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;• }

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

A First Book of ANSI C, Fourth Edition 88

• 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)

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

A First Book of ANSI C, Fourth Edition 89

Computing Sums and Averages Using a for Loop

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

A First Book of ANSI C, Fourth Edition 90

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

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

A First Book of ANSI C, Fourth Edition 91

Technique 1: Selection within a Loop

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

A First Book of ANSI C, Fourth Edition 92

Technique 2: Input Data Validation

Same code used in lines 6-7!

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

A First Book of ANSI C, Fourth Edition 93

Technique 2: Input Data Validation (continued)

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

A First Book of ANSI C, Fourth Edition 94

Technique 3: Interactive Loop Control

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

A First Book of ANSI C, Fourth Edition 95

Technique 4: Evaluating Equations

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

A First Book of ANSI C, Fourth Edition 96

Technique 4: Evaluating Equations (continued)

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

A First Book of ANSI C, Fourth Edition 97

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.

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

A First Book of ANSI C, Fourth Edition 98

• 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 --+ */

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

A First Book of ANSI C, Fourth Edition 99

• 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.

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

A First Book of ANSI C, Fourth Edition 100

• 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.

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

A First Book of ANSI C, Fourth Edition 101

• Proram 5.19

• # include <stdio.h>• 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;• }

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

A First Book of ANSI C, Fourth Edition 102

• 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

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

A First Book of ANSI C, Fourth Edition 103

• 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.

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

A First Book of ANSI C, Fourth Edition 104

• Program 5.20

• # include <stdio.h>• 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;• }

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

A First Book of ANSI C, Fourth Edition 105

• 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.

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

A First Book of ANSI C, Fourth Edition 106

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.

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

A First Book of ANSI C, Fourth Edition 107

• 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;

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

A First Book of ANSI C, Fourth Edition 108

• 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

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

A First Book of ANSI C, Fourth Edition 109

• 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:

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

A First Book of ANSI C, Fourth Edition 110

• 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);

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

A First Book of ANSI C, Fourth Edition 111

• 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.

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

A First Book of ANSI C, Fourth Edition 112

• 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.

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

A First Book of ANSI C, Fourth Edition 113

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:

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

A First Book of ANSI C, Fourth Edition 114

• do• {• printf (“%\n Enter an identification number:

“);• scanf (“%f”, &idNum);• }• whilie (idNum < 1000 ︳︳ idNum >1999);

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

A First Book of ANSI C, Fourth Edition 115

• 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

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

A First Book of ANSI C, Fourth Edition 116

• do • {• prntf (“\n Enter an identification number : “);• scanf (“%f”. &idNum);• if (idNum < 1000 ︳︳ idBun > 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*/

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

A First Book of ANSI C, Fourth Edition 117

• 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.