Top Banner
Iteration in C H&K Chapter 5 Instructor – Gokcen Cilingir Cpt S 121 (July 1, 2011) Washington State University
23

Iteration in C H&K Chapter 5

Jan 06, 2016

Download

Documents

makan

Iteration in C H&K Chapter 5. Instructor – Gokcen Cilingir Cpt S 121 (July 1, 2011) Washington State University. Control Structures. - PowerPoint PPT Presentation
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: Iteration in C H&K Chapter 5

Iteration in CH&K Chapter 5

Instructor – Gokcen Cilingir

Cpt S 121 (July 1, 2011)

Washington State University

Page 2: Iteration in C H&K Chapter 5

Control Structures Remember, in the very first lecture we talked about

how algorithms are put together, and discussed sequential, conditional (selection) and iterative instructions.

Sequential instructionso do them in the order given

Conditional instructionso do them if a condition is true

Iterative instructionso do them while a condition is true

So far, we’ve examined ways to translate sequential and conditional instructions we have in our algorithms into C programs. Today we’re going to see what C provides us to be able to carry out iterative instructions.

Page 3: Iteration in C H&K Chapter 5

Motivation example In Lab 2 Task 1, we wrote a program that does the

following:◦ Carries out following task 10 times:

Reads a character from the input file Prints corresponding ASCII value to the output file Update statistics on numLines, numAlpha, and numDigits.

◦ Prints out the final statistics to an output file

ch = read_character(infile);ascii = determine_ascii_value(ch);print_int(outfile_ascii, ascii);numLines= number_lines(ch, numLines);numDigits = number_digits(ch, numDigits);numAlpha = number_alphas(ch, numAlpha);

Page 4: Iteration in C H&K Chapter 5

Motivation example (cont’d) In Lab 2 Task 1, we wrote a program that does the

following:◦ Carries out following task 10 times:

Reads a character from the input file Prints corresponding ASCII value to the output file Update statistics on numLines, numAlpha, and numDigits.

◦ Prints out the final statistics to an output fileint counter = 0;while (counter < 10){

ch = read_character(infile);ascii = determine_ascii_value(ch);print_int(outfile_ascii, ascii);numLines= number_lines(ch, numLines);numDigits = number_digits(ch, numDigits);numAlpha = number_alphas(ch, numAlpha);counter += 1;

}

Page 5: Iteration in C H&K Chapter 5

5

How to decide when a loop is needed

Sometimes, problem statement explicitly tells you to carry out a procedure a number of times, like in the case of the motivation example: read and process 10 characters. My rule of thumb is: if you need to do something more than 3 times, consider using a loop statement.

Sometimes, problem statement doesn’t imply the need for a loop, but the algorithm you design to solve the problem, may require a loop. Think about the Greatest Common Divisor (GCD) problem (introduced in Lecture 1).

Are any steps repeated in your algorithm? ◦ No No loop required◦ Yes Do you know in advance how many steps are

repeated? No Use a conditional loop Yes Use a counting loop

Page 6: Iteration in C H&K Chapter 5

Loop patterns Counting loop (for or while): executes a fixed

number of times

Sentinel-controlled or Endfile-Controlled loop (for or while): process data until a special value is encountered, e.g., end-of-file

Input validation loop (do-while): repeatedly accept interactive input until a value within a specified range is entered

General conditional loop (while, for): repeatedly process data until a desired condition is met

C. Hundhausen, A. O’Fallon

Page 7: Iteration in C H&K Chapter 5

7C. Hundhausen, A.

O’Fallon

Counter Loops (1) Pseudocode for a counter loop:

Set loop counter to 0while (loop counter < final count) … (Do data processing) add 1 to loop counterendwhile

Page 8: Iteration in C H&K Chapter 5

8C. Hundhausen, A.

O’Fallon

Counter Loops (2) Implementing Counter Loops:

the while loop

while (<repetition-condition>)

{<body>

}

Page 9: Iteration in C H&K Chapter 5

9C. Hundhausen, A.

O’Fallon

Counter Loops (3) Notes on while loops:

◦ <repetition-condition> is evaluated at beginning of loop. If it evaluates to true, the loop body is executed. If it evaluates to false, control shifts to first statement after loop body

◦ <body> contains one or more C statements◦ After last statement in <body> is executed,

control is shifted back to beginning of loop, and <repetition-condition> is re-evaluated.

◦ “Progress” must be made within the loop. That is, something must be done so that <repetition-condition> eventually evaluates to false. Otherwise we have an “infinite loop”

Page 10: Iteration in C H&K Chapter 5

Counter Loops (4)

int counter = 0;while (counter < 10){

ch = read_character(infile);ascii = determine_ascii_value(ch);print_int(outfile_ascii, ascii);numLines= number_lines(ch, numLines);numDigits = number_digits(ch, numDigits);numAlpha = number_alphas(ch, numAlpha);counter = counter + 1;

}

repetition condition

initializing the counter

advancing the counter

Page 11: Iteration in C H&K Chapter 5

11C. Hundhausen, A.

O’Fallon

Counter Loops (5) Another alternative for

implementing Counter Loops: the for loop

for (<initialization>; <repetition-condition>; <update-expression>) {

<body>}

Page 12: Iteration in C H&K Chapter 5

12C. Hundhausen, A.

O’Fallon

Counter Loops (6) Notes on for loops:

◦ <initialization> statement initializes the loop control variables before loop is executed the first time

◦ <repetition-condition> is tested at beginning of loop. If it is true, loop <body> is executed.

◦ <body> contains one or more C statements

◦ After last statement in <body> is executed, control is shifted back to beginning of loop. Then, <update-expression> is executed. Finally, <repetition-condition> is re-evaluated.

◦ As with while loops, the <update-expression> must define “progress.” That is, something must be done so that <repetition-condition> eventually evaluates to false. Otherwise we have an “infinite loop”

Page 13: Iteration in C H&K Chapter 5

Counter Loops (7)

int counter; for(counter = 0; counter< 10; counter = counter +1){

ch = read_character(infile);ascii = determine_ascii_value(ch);print_int(outfile_ascii, ascii);numLines= number_lines(ch, numLines);numDigits = number_digits(ch, numDigits);numAlpha = number_alphas(ch, numAlpha);

}

initialization repetition condition update expression

Page 14: Iteration in C H&K Chapter 5

14C. Hundhausen, A.

O’Fallon

Aside: Compound Assignment Operators Notice that the <update-expression>s in

loops are often of the form:

count = count + 1

C defines special assignment operators to define statements of this form more compactly:

Expression Equivalent expression

count = count +incr count += incr

count = count - incr count -= incr

count = count * factor

count *= factor

count = count / factor

count /= factor

count = count % factor

count %= factor

Page 15: Iteration in C H&K Chapter 5

15C. Hundhausen, A.

O’Fallon

Aside: Increment and Decrement Operators (1) The ++ and -- operators take a single

variable as their operands. The side effect of the operator is to increment or decrement its operand by one:◦ count++ has the effect of count = count + 1◦ count-- has the effect of count = count – 1

Note: ++ and -- can be placed either before or after their variable operator:◦ Pre-increment or pre-decrement (e.g., +

+count, --count ): value of expression is value of variable after the increment or decrement is applied

◦ Post-increment of post-decrement (e.g., count++, count--): value of expression is value of variable before the increment or decrement is applied

Page 16: Iteration in C H&K Chapter 5

16C. Hundhausen, A.

O’Fallon

Aside: Increment and Decrement Operators (2) You try it: What are the values of i, j, and k after each of the following statements is executed?int i, j, k;i = 2;j = 3 + i++; k = 3 + ++i; i *= ++k + j--; i /= k-- + ++j;

Page 17: Iteration in C H&K Chapter 5

17C. Hundhausen, A.

O’Fallon

Counter Loops (8) Notice that we can rewrite our previous

while loop with these new operators:

int counter = 0;while (counter < 10){

ch = read_character(infile);ascii = determine_ascii_value(ch);print_int(outfile_ascii, ascii);numLines= number_lines(ch, numLines);numDigits = number_digits(ch, numDigits);numAlpha = number_alphas(ch, numAlpha);counter++;

}

Page 18: Iteration in C H&K Chapter 5

18C. Hundhausen, A.

O’Fallon

Counter Loops (9) Notice that we can also rewrite our previous

for loop with these new operators:

int counter; for(counter = 0; counter< 10; counter++){

ch = read_character(infile);ascii = determine_ascii_value(ch);print_int(outfile_ascii, ascii);numLines= number_lines(ch, numLines);numDigits = number_digits(ch, numDigits);numAlpha = number_alphas(ch, numAlpha);

}

Page 19: Iteration in C H&K Chapter 5

Example problem – solution with while

Problem statement: Find average of 10 floating point numbers taken from the user

int counter = 0;double sum = 0;double number = 0.0;

printf ("Enter 10 floating point numbers for me:");

while (counter <10){

scanf("%lf", &number);sum += number;counter++;

}

printf("Average of them is: %lf\n", sum/counter);

Accumulating a value

Page 20: Iteration in C H&K Chapter 5

Example problem- solution with for

Problem statement: Find average of10 floating point numbers taken from the user

int counter = 0;double sum = 0;double number = 0.0;

printf ("Enter 10 floating point numbers for me:");

sum = 0;for (counter = 0; counter <10; counter++){

scanf("%lf", &number);sum += number;

}

printf("Average of them is: %lf\n", sum/counter);

Notice the use of comma operator

Page 21: Iteration in C H&K Chapter 5

21

It’s OK to have loop increments other than 1!

Page 22: Iteration in C H&K Chapter 5

22C. Hundhausen, A.

O’Fallon

Next Lecture… We'll discuss some additional

loop patterns:◦ Conditional loops◦ Sentinel-controlled loops & end-file-

controlled loops◦ Flag-controlled loops

Page 23: Iteration in C H&K Chapter 5

23

ReferencesJ.R. Hanly & E.B. Koffman,

Problem Solving and Program Design in C (6th Ed.), Addison-Wesley, 2010

P.J. Deitel & H.M. Deitel, C How to Program (5th Ed.), Pearson Education , Inc., 2007.