Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

Computer Science 1620 Loops.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Loops and Files.
CS 117 Spring 2002 Repetition Hanly Chapter 4 Friedman-Koffman Chapter 5.
Computer Programming 1 Repetition. Computer Programming 2 Objectives Repetition structures Study while and do loops Examine for loops A practical example.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Control Structures II (Repetition)
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
C++ Programming Lecture 6 Control Structure II (Repetition) By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Chapter 05 (Part III) Control Statements: Part II.
Control Structures Repetition or Iteration or Looping Part II.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Fundamental Programming Fundamental Programming for Loops.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
1 do-while Statement 2 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Week 4 – Repetition Structures / Loops
Control Structures II (Repetition)
Chapter 2.2 Control Structures (Iteration)
Programming Fundamentals
Lecture 4B More Repetition Richard Gesick
Looping.
Repetition Control Structure
Chapter 2.2 Control Structures (Iteration)
Lab5 PROGRAMMING 1 Loop chapter4.
2.6 The if/else Selection Structure
Control Statements Paritosh Srivastava.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Presentation transcript:

Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University

178110: Computer Programming (II/2546) 2 Introduction to Iteration Iteration is the repetition of a statement Why iterate? Use the computer’s speed to do the same task faster than if done by hand Avoid writing the same statements over and over again Programs can be made general enough to handle other types of data

178110: Computer Programming (II/2546) 3 C++ Iteration Statements Three types of iteration statements for statement Example: for (int j = 0; j < 10; j++) {…} do … while statement Example: int j = 0; do { …. j++; } while (j < 10); while statement Example: int j = 0; while (j < 10) {… j++;} Iteration statements are also called loops

178110: Computer Programming (II/2546) 4 The for Statement Syntax: for (init; cond; update) { statement;} init expression is used to declare and/or initialize control variable(s) for the loop cond expression is used to determine whether the loop should continue iterating update expression is used to update the control variable(s)

178110: Computer Programming (II/2546) 5 Flow Chart of “if” Statement condition statement true false

178110: Computer Programming (II/2546) 6 Flow Chart of “for” Statement condition statement true false statement

178110: Computer Programming (II/2546) 7 คำสั่ง กำหนดค่าเริ่มต้น นิพจน์ ตรรกศาส ตร์ เท็จ คำสั่ง เปลี่ยนแปลงค่า ชุดคำสั่ง จริง ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง Flowchart แสดงลำดับการ ทำงานของคำสั่ง for

178110: Computer Programming (II/2546) 8 Steps in Executing ‘for’ loop for (init; cond; update) { statement; } 1. Evaluate the init expression 2. If the value of the cond expression is false, terminate the loop 3. If the value of the cond expression is true, execute the statement and evaluate the update expression 4. Repeat steps 2-3

178110: Computer Programming (II/2546) 9 Ex1: Sum of Consecutive Integers long sum = 0; int n, i = 1; cout << “Enter a positive integer:”; cin >> n; for (int i=1; i <= n; i++) sum += i++; cout << “The sum of the first “ << n << “ integers is “ << sum << endl; What is the expected output when n = 2, n =3? What is the actual output when n = 2, n = 3?

178110: Computer Programming (II/2546) 10 Ex1: Sum of Consecutive Integers (Cont.) How to add 1,2,…, n using one for loop? for (int i=1; i <= n; i++) sum += i; How to split the above for loop into two loops? for (int i=1; i<= n/2; i++) sum += i; for (int i =n/2; i <= n; i++) sum += i; How to split the above for loop correctly?

178110: Computer Programming (II/2546) 11 Ex1: Sum of Consecutive Integers (Cont.) How to add 1,2,…, n using for loop? for (int i=1; i <= n; i++) sum += i; How to split the above for loop into two loops? for (int i = 1; i < n/2; i++) sum += i; for (int i = n/2; i <= n; i++) sum += i;

178110: Computer Programming (II/2546) 12 Ex2: Find Factorial Numbers long bound, f = 1; cout << “Enter a positive integer:”; cin >> bound; cout << "Factorial numbers < " << bound << "\n"; for (int i = 2; f <= bound; i++) { cout << f << “ “; f *= i; } What is the output when bound = 5, 6, and 12?

178110: Computer Programming (II/2546) 13 Ex3: Using a Descending for Loop int main() { for (int i = 10; i > 0; i--) cout << i << “ “; } What is the output? This program prints the first ten positive integers in a reverse order

178110: Computer Programming (II/2546) 14 Ex4: With a Step Greater Than One long n; cout = 4):”; cin >> n; if (n%2 == 0) cout << n << “ = 2*” << n/2 << endl; else { for (int d = 3; d <= n/2; d+= 2) if (n%d == 0) { cout << n << “ = “ << d << *” << n/d; } cout << n << “ is prime.” << endl; } What is the output when n = 9, n = 12, n = 13? This for loop uses an increment of what number?

178110: Computer Programming (II/2546) 15 Ex5: Using a Sentinel to Control a for Loop int n, max; cout << “Enter positive integers (0 to quit):”; cin >> n; for (max=n; n > 0;) { if (n>max) max = n; cin >> n; } This for loop is controlled by the input variable n It continues until n <= 0 When an input variable controls a variable this way, it is called a sentinel

178110: Computer Programming (II/2546) 16 Ex6: Using More than One Control Variable The for loop in this program uses two control variables for (int m=30, n = 4; m%n > 0; m-=3, n+=2) cout << m << “%” << n << “= “ << m%n << endl; 30%4=2 27%6=3 Two control variables m and n are used in this loop What are the values of m and n that terminate the loop?

178110: Computer Programming (II/2546) 17 Nested Loops for (int x=1; x <=3; x++) { for (int y =1; y <= 3; y++) { … } } Loops inside other loops Start with outer jump to inner loop Inner loop continues until complete Back to outer loop and start again

178110: Computer Programming (II/2546) 18 Ex7: Nesting for Loops for (int x=1; x <=3; x++) { for (int y =1; y <= 3; y++) cout << setw(10) << x*y; cout << endl; } What is the output?

178110: Computer Programming (II/2546) 19 Ex7: Nesting for Loops (Cont.) If we want to get the output How to write the for loops to achieve such output? for (int x =1; x<= 3; x++) { for (int y=2; y <= 6; y +=2) cout << setw(10) << x*y; cout << endl; }

178110: Computer Programming (II/2546) 20 The while Statement Syntax: while (condition) statement; Condition is an integral expression If the value of the expression is zero (false), the statement is not executed If the value of the expression is non-zero (true), the statement is executed repeatedly until the expression is evaluated to zero Condition must be enclosed by parentheses

178110: Computer Programming (II/2546) 21 Flowchart แสดงลำดับการ ทำงานของคำสั่ง while คำสั่ง กำหนดค่าเริ่มต้น นิพจน์ ตรรกศาส ตร์ เท็จ คำสั่ง เปลี่ยนแปลงค่า ชุดคำสั่ง จริง ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง

178110: Computer Programming (II/2546) 22 while Statement Format: initial statements while (conditional expression) { statements update statements } Example: count = 0; while (count < n) { cout << "*"; count = count + 1; }

178110: Computer Programming (II/2546) 23 Ex8: Sum of Consecutive Integers (Using While) How to write a while loop to compute the …+n for an input integer n int n, i = 1; cin >> n; long sum = 0; while (i <= n) sum += i++; cout << “The sum of the first “ << n << “ integers is “ << sum;

178110: Computer Programming (II/2546) 24 Ex9: Repeat a Computation cin >> x; while (x > 0) { cout << “SQRT(“ << x << “)=“ << sqrt(x); cin >> x; } The condition (x > 0) uses the variable x to control the loop The variable x that uses this way is called a loop control variable

178110: Computer Programming (II/2546) 25 Terminating a Loop while (i < = n) sum += i++; while (true) { if (i > n) _____________ sum += i++; } Using a break statement inside a loop causes the loop to terminate immediately, without having to finish executing the remaining statements in the loop block

178110: Computer Programming (II/2546) 26 Terminating a Loop (Cont.) The exit() function can also provide another way to terminate a program, which just also terminate a loop while (true) { if (i > n) exit(0); sum += i++; } cout << “sum is “ << sum << endl; What is the different effect of ‘break’ and ‘exit’? What is another function that we can use to terminate a loop?

178110: Computer Programming (II/2546) 27 Aborting An Infinite Loop int i = 0; int sum = 0; while (true) { sum += i++; } Without some termination mechanism, the loop will run forever To abort its execution after it starts, press +C

178110: Computer Programming (II/2546) 28 The do… while Statement Syntax: do statement while (condition); It repeatedly executes the statement and then evaluates the condition until the condition evaluates to false It works the same as the while statement except Its condition is evaluated at the end of the loop instead of at the beginning It means that a do…while loop will always iterate at least once, regardless of the value of its control condition

178110: Computer Programming (II/2546) 29 Flowchart ของคำสั่ง do..while ชุดคำสั่ง เท็ จ นิพจน์ ตรรกศาสตร์ จริ ง คำสั่ง เปลี่ยนแปลงค่า มีการทำชุดคำสั่ง อย่างน้อยหนึ่งครั้งเสมอ ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง

178110: Computer Programming (II/2546) 30 Ex10: Factorial Numbers (do … while) long bound, f = 1; for (int i = 2; f <= bound; i++) { cout << f << “ “; f *= i;} int i = 2; do { cout << f << “ “; f *= i; i++; } while (f <= bound);

178110: Computer Programming (II/2546) 31 The break Statement We have already seen the break statement used in the switch statement When it executes, it terminates the loop, ‘breaking out’ of the iteration at that point It provides extra flexibility in the control loops

178110: Computer Programming (II/2546) 32 Using a break to terminate a Loop while (true) { if (i > n) break; sum += i++; } As long as (i <= n) the loop will continue But as soon as (i > n), the break statement executes, immediately terminating the loop

178110: Computer Programming (II/2546) 33 Ex11: Controlling Input with a Sentinel int n, count = 0, sum = 0; for (; ;) // forever { cout << “\t” << count+1 << “: “; cin >> n; if (n <= 0) break; ++count; sum += n; } cout << “The average of those “ << count << “ numbers is “ << float(sum)/count << endl; What is the output of this program n = 4, 2, 0?

178110: Computer Programming (II/2546) 34 Ex12: Using a break with Nested Loops for (int x=1; x <=3; x++) { for (int y = 1; y <=3; y++) if (y>x) break; else cout << setw(10) << x*y; cout << endl; }

178110: Computer Programming (II/2546) 35 The continue Statement The break statement skips the rest of the statements in the loop’s block, jumping immediately to the next statement outside of the loop The continue statement is similar but It continues the loop after skipping the remaining statements in its current iteration

178110: Computer Programming (II/2546) 36 Ex13: Using continue & break int n; for (;;) { cout << “Enter an integer: “; cin >> n; if (n %2 == 0) continue; if (n %3 == 0) break; cout << “\tBottom of loop.\n”; } cout << “\tOutside of loop.\n”; What is the output when n = 7, 4, and 9?

178110: Computer Programming (II/2546) 37 The goto Statement The goto statement is another kind of jump statement Its destination is specified by a label within the statement A label is simply an identifier followed by a colon placed in front of a statement Labels work like the case statements inside a switch statement: they specify the destination of the jump

178110: Computer Programming (II/2546) 38 Ex14: Using a goto for (int i=0; i < N; i++) { for (int j=0; j < N; j++) { if (i+j>N) goto esc; else cout << i+j << “ “; cout << “ *”; } esc: cout << “.” << endl; What is the output when N = 3?

178110: Computer Programming (II/2546) 39 Ex15: Generating Random Numbers #include int main() { unsigned seed; cout << “Enter seed:”; cin >> seed; srand(seed); // initialize the seed for (int i = 0; i < 8; i++) cout << rand() << endl; }

178110: Computer Programming (II/2546) 40 Ex15: Output Enter seed:

178110: Computer Programming (II/2546) 41 Ex16: Generating Random Numbers in a Given Range int min, max; int range = max – min + 1; for (int i = 0; i < 5; i++) { int ra = rand(); int r = ra/100%range + min; cout << “ra is “ << r << “ r is “ << r << endl; } cout << endl;

178110: Computer Programming (II/2546) 42 Ex16: Output seed = Enter minimum and maximum:1 100 ra is r is 40 ra is 4099 r is 41 ra is r is 13 ra is r is 68 ra is r is 57

178110: Computer Programming (II/2546) 43 Ex17: Using a Flag to Break bool done = false; int i = 1, j = 1; while (!done) { if (i+j == 10) done = true; else cout << i + j << “ “; i++; j++; } Output:

178110: Computer Programming (II/2546) 44 Review of while, for, and do- while Loops while - Most commonly used when repetition is not counter controlled for - Counting loop - When number of repetitions is known ahead of time and can be controlled by a counter; also convenient for loops involving non counting loop control with simple initialization and updates do-while - Convenient when at least one repetition of loop body must be ensured. Post test condition after execution of body.

178110: Computer Programming (II/2546) 45 Debugging & Testing Programs Insert extra diagnostic output statements to display intermediate results at critical points in your program while (count < 10) sum += count; while (count < 10) { cout << “count is “ << count << endl; sum += count; count++; }

178110: Computer Programming (II/2546) 46 Common Programming Errors Omitting brace while (x > xbig) x -= 2; xbig++; is excuted as while (x > xbig) { x -= 2; } xbig++; Omitting a closing brace Misuse of = for ==