Download presentation
Presentation is loading. Please wait.
Published byHarry Freeman Modified over 8 years ago
1
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University
2
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
3
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
4
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)
5
178110: Computer Programming (II/2546) 5 Flow Chart of “if” Statement condition statement true false
6
178110: Computer Programming (II/2546) 6 Flow Chart of “for” Statement condition statement true false statement
7
178110: Computer Programming (II/2546) 7 คำสั่ง กำหนดค่าเริ่มต้น นิพจน์ ตรรกศาส ตร์ เท็จ คำสั่ง เปลี่ยนแปลงค่า ชุดคำสั่ง จริง ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง Flowchart แสดงลำดับการ ทำงานของคำสั่ง for
8
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
9
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?
10
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?
11
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;
12
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?
13
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? 10 9 8 7 6 5 4 3 2 1 This program prints the first ten positive integers in a reverse order
14
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?
15
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
16
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?
17
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
18
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? 1 2 3 2 4 6 3 6 9
19
178110: Computer Programming (II/2546) 19 Ex7: Nesting for Loops (Cont.) If we want to get the output 2 4 6 4 8 12 6 12 18 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; }
20
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
21
178110: Computer Programming (II/2546) 21 Flowchart แสดงลำดับการ ทำงานของคำสั่ง while คำสั่ง กำหนดค่าเริ่มต้น นิพจน์ ตรรกศาส ตร์ เท็จ คำสั่ง เปลี่ยนแปลงค่า ชุดคำสั่ง จริง ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง
22
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; }
23
178110: Computer Programming (II/2546) 23 Ex8: Sum of Consecutive Integers (Using While) How to write a while loop to compute the 1+2+3+…+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;
24
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
25
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
26
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?
27
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
28
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
29
178110: Computer Programming (II/2546) 29 Flowchart ของคำสั่ง do..while ชุดคำสั่ง เท็ จ นิพจน์ ตรรกศาสตร์ จริ ง คำสั่ง เปลี่ยนแปลงค่า มีการทำชุดคำสั่ง อย่างน้อยหนึ่งครั้งเสมอ ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง
30
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);
31
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
32
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
33
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?
34
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; } 1 2424 36 9
35
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
36
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?
37
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
38
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?
39
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; }
40
178110: Computer Programming (II/2546) 40 Ex15: Output Enter seed:32 26213 19710 22126 11516 30247 14731 20276 11196
41
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;
42
178110: Computer Programming (II/2546) 42 Ex16: Output seed = 1073528463 Enter minimum and maximum:1 100 ra is 23947 r is 40 ra is 4099 r is 41 ra is 21201 r is 13 ra is 26796 r is 68 ra is 25664 r is 57
43
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: 2 4 6 8
44
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.
45
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++; }
46
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 ==
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.