1 / 23

Iteration in C H&K Chapter 5

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

makan
Télécharger la présentation

Iteration in C H&K Chapter 5

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Iteration in CH&K Chapter 5 Instructor – GokcenCilingir 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 • do them in the order given • Conditional instructions • do them if a condition is true • Iterative instructions • 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. 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

  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. Counter Loops (2) • Implementing Counter Loops: the while loop while (<repetition-condition>) { <body> }

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

  10. Counter Loops (4) initializing the counter 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 advancing the counter

  11. Counter Loops (5) • Another alternative for implementing Counter Loops: the for loop for (<initialization>; <repetition-condition>; <update-expression>) { <body> }

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

  13. Counter Loops (7) repetition condition update expression initialization 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); }

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

  15. 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. 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? inti, j, k; i = 2; j = 3 + i++; k = 3 + ++i; i *= ++k + j--; i /= k-- + ++j;

  17. 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. 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 Notice the use of comma operator 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);

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

  22. Next Lecture… • We'll discuss some additional loop patterns: • Conditional loops • Sentinel-controlled loops & end-file-controlled loops • Flag-controlled loops

  23. References • J.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.

More Related