460 likes | 490 Views
This chapter introduces the concept of iteration and its importance in computer programming. It covers the three types of iteration statements in C++ and provides examples and flowcharts to illustrate their usage. The chapter also includes exercises to practice using iteration statements.
E N D
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University
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)
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)
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)
false condition true statement Flow Chart of “if” Statement 178110: Computer Programming (II/2546)
statement statement Flow Chart of “for” Statement false condition true 178110: Computer Programming (II/2546)
Flowchart แสดงลำดับการทำงานของคำสั่งfor คำสั่งกำหนดค่าเริ่มต้น เท็จ นิพจน์ ตรรกศาสตร์ ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง จริง ชุดคำสั่ง คำสั่งเปลี่ยนแปลงค่า 178110: Computer Programming (II/2546)
Steps in Executing ‘for’ loop for (init; cond; update) { statement; } • Evaluate the init expression • If the value of the cond expression is false, terminate the loop • If the value of the cond expression is true, execute the statement and evaluate the update expression • Repeat steps 2-3 178110: Computer Programming (II/2546)
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)
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)
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)
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)
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 178110: Computer Programming (II/2546)
Ex4: With a Step Greater Than One long n; cout << “Enter a positive integer (>= 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)
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)
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)
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)
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 178110: Computer Programming (II/2546)
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; } 178110: Computer Programming (II/2546)
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)
Flowchart แสดงลำดับการทำงานของคำสั่งwhile คำสั่งกำหนดค่าเริ่มต้น เท็จ นิพจน์ ตรรกศาสตร์ ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง จริง ชุดคำสั่ง คำสั่งเปลี่ยนแปลงค่า 178110: Computer Programming (II/2546)
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)
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; 178110: Computer Programming (II/2546)
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)
while (i < = n) sum += i++; while (true) { if (i > n) _____________ sum += i++; } Terminating a Loop 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)
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)
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 <Ctrl>+C 178110: Computer Programming (II/2546)
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)
มีการทำชุดคำสั่ง อย่างน้อยหนึ่งครั้งเสมอ คำสั่งเปลี่ยนแปลงค่า ชุดคำสั่ง ทำชุดคำสั่งซ้ำ ถ้านิพจน์ตรรกศาสตร์ ยังเป็นจริง จริง นิพจน์ตรรกศาสตร์ เท็จ Flowchart ของคำสั่ง do..while 178110: Computer Programming (II/2546)
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)
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)
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)
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)
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 2 4 3 6 9 178110: Computer Programming (II/2546)
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)
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)
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)
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)
Ex15: Generating Random Numbers #include <cstdlib> #include <iostream> 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)
Ex15: Output Enter seed:32 26213 19710 22126 11516 30247 14731 20276 11196 178110: Computer Programming (II/2546)
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)
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 178110: Computer Programming (II/2546)
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 178110: Computer Programming (II/2546)
Review of while, for, anddo-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)
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)
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 == 178110: Computer Programming (II/2546)