Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Iteration in C H&K Chapter 5 Instructor – Gokcen Cilingir Cpt S 121 (July 1, 2011) Washington State University."— Presentation transcript:

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

2 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 instructions o do them in the order given Conditional instructions o do them if a condition is true Iterative instructions o 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.

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

4 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 file 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 += 1; }

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

6 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

7 7 Counter Loops (1) Pseudocode for a counter loop: Set loop counter to 0 while (loop counter < final count) … (Do data processing) add 1 to loop counter endwhile

8 C. Hundhausen, A. O’Fallon8 Counter Loops (2) Implementing Counter Loops : the while loop while ( ) { }

9 C. Hundhausen, A. O’Fallon9 Counter Loops (3) Notes on while loops: ◦ 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 ◦ contains one or more C statements ◦ After last statement in is executed, control is shifted back to beginning of loop, and is re-evaluated. ◦ “Progress” must be made within the loop. That is, something must be done so that eventually evaluates to false. Otherwise we have an “infinite loop”

10 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

11 C. Hundhausen, A. O’Fallon11 Counter Loops (5) Another alternative for implementing Counter Loops : the for loop for ( ; ; ) { }

12 C. Hundhausen, A. O’Fallon12 Counter Loops (6) Notes on for loops: ◦ statement initializes the loop control variables before loop is executed the first time ◦ is tested at beginning of loop. If it is true, loop is executed. ◦ contains one or more C statements ◦ After last statement in is executed, control is shifted back to beginning of loop. Then, is executed. Finally, is re- evaluated. ◦ As with while loops, the must define “progress.” That is, something must be done so that eventually evaluates to false. Otherwise we have an “infinite loop”

13 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 conditionupdate expression

14 C. Hundhausen, A. O’Fallon14 Aside: Compound Assignment Operators Notice that the s in loops are often of the form: count = count + 1 C defines special assignment operators to define statements of this form more compactly: ExpressionEquivalent expression count = count +incrcount += incr count = count - incrcount -= incr count = count * factorcount *= factor count = count / factorcount /= factor count = count % factorcount %= factor

15 C. Hundhausen, A. O’Fallon15 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

16 C. Hundhausen, A. O’Fallon16 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;

17 C. Hundhausen, A. O’Fallon17 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++; }

18 C. Hundhausen, A. O’Fallon18 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); }

19 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

20 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

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

22 C. Hundhausen, A. O’Fallon22 Next Lecture… We'll discuss some additional loop patterns: ◦ Conditional loops ◦ Sentinel-controlled loops & end-file- controlled loops ◦ Flag-controlled loops

23 23 References J.R. Hanly & E.B. Koffman, Problem Solving and Program Design in C (6 th Ed.), Addison- Wesley, 2010 P.J. Deitel & H.M. Deitel, C How to Program (5 th Ed.), Pearson Education, Inc., 2007.


Download ppt "Iteration in C H&K Chapter 5 Instructor – Gokcen Cilingir Cpt S 121 (July 1, 2011) Washington State University."

Similar presentations


Ads by Google