 Download Download Presentation Repetitive Structures

# Repetitive Structures

Download Presentation ## Repetitive Structures

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Repetitive Structures The Ohio State University

2. logExample.cpp // example of log(k) for k = 1,2,..,8 . . . int main() { cout << "log(1) = " << log(1.0) << endl; cout << "log(2) = " << log(2.0) << endl; cout << "log(3) = " << log(3.0) << endl; cout << "log(4) = " << log(4.0) << endl; cout << "log(5) = " << log(5.0) << endl; cout << "log(6) = " << log(6.0) << endl; cout << "log(7) = " << log(7.0) << endl; cout << "log(8) = " << log(8.0) << endl; return 0; } The Ohio State University

3. logExample.cpp ... cout << "log(1) = " << log(1.0) << endl; cout << "log(2) = " << log(2.0) << endl; cout << "log(3) = " << log(3.0) << endl; cout << "log(4) = " << log(4.0) << endl; cout << "log(5) = " << log(5.0) << endl; cout << "log(6) = " << log(6.0) << endl; cout << "log(7) = " << log(7.0) << endl; cout << "log(8) = " << log(8.0) << endl; ... > logExample.exe log(1) = 0 log(2) = 0.693147 log(3) = 1.09861 log(4) = 1.38629 log(5) = 1.60944 log(6) = 1.79176 log(7) = 1.94591 log(8) = 2.07944 The Ohio State University

4. Repetition Structures (Loops) • Motivation: If we want to repeat essentially the same code say 1000 times we should not have to write 100 lines of code! • We need a new statement to help us execute repetitive code The Ohio State University

5. logWhile.cpp // example of while loop for log(k) for k = 1,2,..,8 . . . int main() { int k(0); k = 1; while (k <= 8) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } return 0; } The Ohio State University

6. logWhile.cpp ... k = 1; while (k <= 8) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } ... > logWhile.exe log(1) = 0 log(2) = 0.693147 log(3) = 1.09861 log(4) = 1.38629 log(5) = 1.60944 log(6) = 1.79176 log(7) = 1.94591 log(8) = 2.07944 The Ohio State University

7. while Loops • The while statement syntax: while (conditional expression) { statement1; statement2; ... } The Ohio State University

8. How while Loops Work • First test the conditional expression If it is true, then execute the statement(s) within the loop structure is/are executed • After the statement(s) are executed, we try to repeat the process If the condition is still true, then we will execute the statement(s) again Thus, while the condition is true, keep repeating • If the condition ever evaluates to false, then stop the while statement; the program continues execution after the while statement The Ohio State University

9. Control Flow of a while Loop The Ohio State University

10. logWhile.cpp … while (k <= 8) { cout<< "log(" << k << ") = " << log(double(k)) << endl; k++; } return 0; } • The variable k , which appears in the conditional expression, is called a loop variable • It is an important variable because its value determines whether the loop stops or keeps going • The condition is the most difficult part of writing a loop The Ohio State University

11. While Example count = 1; while (count <= 10) { cout << count << “ “; count++; //increment count! } • Output is “1 2 3 4 5 6 7 8 9 10” • The behavior of the loop is determined by the loop variable(s): • Initialization of the loop variable • Use in the condition determines continuation or end of the loop • Update of the loop variable The Ohio State University

12. Control Flow of the Example Program The Ohio State University

13. Repetition Structures 2 • Motivation 2: Allow repetition of code based on input For example,a program should be able to output n lines of cout statements where n is a user input The Ohio State University

14. logWhile2.cpp ... int main() { int n(0), k(0); cout << "Enter number of logarithms to compute: "; cin >> n; k = 1; while (k <= n) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } return 0; } The Ohio State University

15. logWhile2.cpp ... cout << "Enter number of logarithms to compute: "; cin >> n; k = 1; while (k <= n) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } ... > logWhile2.exe Enter number of logarithms to compute: 5 log(1) = 0 log(2) = 0.693147 log(3) = 1.09861 log(4) = 1.38629 log(5) = 1.60944 The Ohio State University

16. logWhile2.cpp ... cout << "Enter number of logarithms to compute: "; cin >> n; k = 1; while (k <= n) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } ... What happens here? > logWhile2.exe Enter number of logarithms to compute: -3 ??? The Ohio State University

17. Repetition Structures 3 • If a program receives incorrect input, it can repeatedly prompt for the correct input The Ohio State University

18. logWhile3.cpp // example of while loop to prompt for correct input ... int main() { double x(0.0); cout << "Enter number: "; cin >> x; while (x <= 0) { cout << "Input must be positive." << endl; cout << "Enter number: "; cin >> x; } cout << "log(" << x << ") = “ << log(x) << endl; return 0; } The Ohio State University

19. logWhile3.cpp ... cout << "Enter number: "; cin >> x; while (x <= 0) { cout << "Input must be positive." << endl; cout << "Enter number: "; cin >> x; } cout << "log(" << x << ") = " << log(x) << endl; ... > logWhile3.exe Enter number: -4.5 Input must be positive. Enter number: 0 Input must be positive. Enter number: 4.5 log(4.5) = 1.50408 The Ohio State University

20. logWhileError.cpp // example of a while loop with a logical error . . . int main() { int k(0); k = 1; while (k <= 8) { cout << "log(" << k << ") = " << log(double(k)) endl; } return 0; } Try running this program The Ohio State University

21. probability.cpp ... int main() { double p(0.0); cout << "Enter probability player A wins 1 game: "; cin >> p; while (p < 0.0 || p > 1.0) { cout << "Input must be in range [0:1]." << endl; cout << "Enter probability player A wins 1 game: "; cin >> p; } cout << "Probability player A loses all 5 games = " << pow((1-p), 5.0) << endl; return 0; } The Ohio State University

22. ... while (p < 0.0 || p > 1.0) { cout << "Input must be in range [0:1]." << endl; cout << "Enter probability player A wins 1 game: "; cin >> p; } ... > probability.exe Enter probability player A wins: 2 Input must be in range [0:1]. Enter probability player A wins: -1 Input must be in range [0:1]. Enter probability player A wins: 0.2 Probability player A loses all 5 games = 0.32768 > The Ohio State University

23. temperature.cpp // print a table converting fahrenheit to celsius ... intfahrenheit(0), min_fahrenheit(0), max_fahrenheit(0); int STEP_SIZE(10); cout << "Enter min and max fahrenheit: "; cin >> min_fahrenheit >> max_fahrenheit; fahrenheit = min_fahrenheit; // loop until fahrenheit is greater than max_fahrenheit while (fahrenheit <= max_fahrenheit) { // convert fahrenheit to celsius float celsius = (fahrenheit - 32.0) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE } ... The Ohio State University

24. temperature.cpp ... int STEP_SIZE(10); ... fahrenheit = min_fahrenheit; // loop until fahrenheit is greater than max_fahrenheit while (fahrenheit <= max_fahrenheit) { // convert fahrenheit to celsius float celsius = (fahrenheit - 32.0) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE } ... > temperature.exe Enter min and max fahrenheit: 20 60 farenheit = 20 celsius = -6.66667 farenheit = 30 celsius = -1.11111 farenheit = 40 celsius = 4.44444 farenheit = 50 celsius = 10 farenheit = 60 celsius = 15.5556 The Ohio State University

25. temperature.cpp ... int STEP_SIZE(10); ... fahrenheit = min_fahrenheit; // loop until fahrenheit is greater than max_fahrenheit while (fahrenheit <= max_fahrenheit) { // convert fahrenheit to celsius float celsius = (fahrenheit - 32.0) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE } ... > temperature.exe Enter min and max fahrenheit: 25 60 farenheit = 25 celsius = -3.88889 farenheit = 35 celsius = 1.66667 farenheit = 45 celsius = 7.22222 farenheit = 55 celsius = 12.7778 The Ohio State University

26. temperature2.cpp ... int STEP_SIZE(5); ... fahrenheit = min_fahrenheit; while (fahrenheit <= max_fahrenheit) { float celsius = (fahrenheit - 32.0) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE } ... > temperature2.exe Enter min and max fahrenheit: 25 60 farenheit = 25 celsius = -3.88889 farenheit = 30 celsius = -1.11111 farenheit = 35 celsius = 1.66667 farenheit = 40 celsius = 4.44444 farenheit = 45 celsius = 7.22222 farenheit = 50 celsius = 10 farenheit = 55 celsius = 12.7778 farenheit = 60 celsius = 15.5556 The Ohio State University

27. temperatureError.cpp // print a table converting fahrenheit to celsius ... intfahrenheit(0), min_fahrenheit(0), max_fahrenheit(0); int STEP_SIZE(10); cout << "Enter min and max fahrenheit: "; cin >> min_fahrenheit >> max_fahrenheit; fahrenheit = min_fahrenheit; // loop until fahrenheit does not equal max_fahrenheit while (fahrenheit != max_fahrenheit) // Note != instead of <= { // convert fahrenheit to celsius float celsius = (fahrenheit - 32.0) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE } ... The Ohio State University

28. sinWhile.cpp (Error) … int main() { double x(0.0); double increment(0.1); cout.setf(ios::fixed); while (x != 1.0) { cout<< x << ": " << sin(x) << " " << cos(x) << endl; x += increment; } return 0; } The Ohio State University

29. for Loops The Ohio State University

30. logFor.cpp // example of for loop for log(k) for k = 1,2,..,8 #include <iostream> #include <cmath> using namespace std; int main() { for (int k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; } return 0; } The Ohio State University

31. logFor.cpp ... for (int k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; } ... > logFor.exe log(1) = 0 log(2) = 0.693147 log(3) = 1.09861 log(4) = 1.38629 log(5) = 1.60944 log(6) = 1.79176 log(7) = 1.94591 log(8) = 2.07944 The Ohio State University

32. for Loop Syntax for (initialize; condition; alter) { statement1; statement2; statement3; statement4; ... } The Ohio State University

33. for Loop Syntax (2) • Initializing list • A statement to set the starting value(s) of variables (normally a loop counter) • Expression • The looping condition • Altering list • Statement that is executed at the end of every loop traversal • Normally determines how the counter is manipulated after each pass through the loop • Important note: At the end of a pass through the loop, the statements in the altering list is executed BEFORE the loop expression is evaluated The Ohio State University

34. How for Loops Work • First, the initialization statements are executed • Then the conditional expression is tested. If it is true, then the statement(s) within the loop structure is/are executed. • Once the end of those statements is reached, then altering statements are executed, and the process is repeated. • If the expression ever evaluates to false, then the loop statement is exited, and the program continues beyond the loop. The Ohio State University

35. Control Flow of a for Loop The Ohio State University

36. for Loop Example for (int k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; } // the while-loop equivalent: int k(0); . . . k = 1; while (k <= 8) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } The Ohio State University

37. for Loop Example2 // Compute n logarithms: for (int k = 1; k <= n; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; } // the while-loop equivalent: int k(0); . . . k = 1; while (k <= n) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } The Ohio State University

38. (Too) Clever for Loop Example double x(0.0); cout << “Enter Number: “; for (cin >> x; x <= 0; cin >> x) // a while loop is better { cout<< "Input must be positive." << endl; cout<< "Enter number: "; } // the while-loop equivalent: double x(0.0); cout << “Enter number: “; cin >> x; while (x <= 0) { cout << "Input must be positive." << endl; cout << "Enter number: "; cin >> x; } cout << "log(" << x << ") = " << log(x) << endl; The Ohio State University

39. for Loops • for loops and while loops are interchangeable • A for loop is a pre-test loop • Whether to use a while or a for loop is a question of style and readability • Use for loops to count from a to b • Use while loops to iterate until some condition is satisfied The Ohio State University

40. for Loop Example4 for (int k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; } cout << k << endl; // SYNTAX ERROR // Variable k can be declared before the for-loop int k(0); for (k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; } cout << k << endl; // What is the value of k? The Ohio State University

41. Using Nested Loops • A loop inside of another loop • Extremely useful and very common for (inti = 1; i <= 5; i++) { cout << “i is now “ << i << endl; //inner (nested) loop for (int j = 1; j <= 4; j++) { cout << “j is now “ << j << endl; } } //What is the output? The Ohio State University

42. The Ohio State University

43. Nested for loops: square.cpp // print a square of x's ... int length(0); cout << "Enter square edge length: "; cin >> length; for (int row = 1; row <= length; row++) { // print length x's for (int col = 1; col <= length; col++) { cout<< "x"; } cout<< endl; // print newline to finish row } ... The Ohio State University

44. Nested for loops: square.cpp ... for (int row = 1; row <= length; row++) { // print length x's for (int col = 1; col <= length; col++) { cout<< "x"; } cout << endl; // print newline to finish row } ... > square.exe Enter square edge length: 6 xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx xxxxxx The Ohio State University

45. Nested for loops: diagonal.cpp // print a diagonal of x's ... int length(0); cout << "Enter diagonal length: "; cin >> length; for (int row = 1; row <= length; row++) { // print (row-1) spaces for (int col = 1; col <= row-1; col++) { cout<< " "; } cout<< "x" << endl; // print x on diagonal } ... The Ohio State University

46. Nested for loops: diagonal.cpp ... for (int row = 1; row <= length; row++) { // print (row-1) spaces for (int col = 1; col <= row-1; col++) { cout<< " "; } cout<< "x" << endl; // print x on diagonal } ... > diagonal.exe Enter diagonal length: 6 x x x x x x The Ohio State University

47. squareError.cpp // version of square.cpp with errors ... int length(0); cout << "Enter square edge length: "; cin >> length; for (int row = 1; row <= length; row++); { // print length x's for (int col = 1; col <= length; col++); { cout<< "x"; } cout<< endl; // print newline to finish row } ... The Ohio State University

48. do-while loops • A do-while loop checks the condition at the end of the loop • Example: char c(‘n’); do { ... //rest of the program cout<< “Do you wish to continue: “; cin>> c; } while (c == ‘y’ || c == ‘Y’); • See text for more details. The Ohio State University

49. Conclusion on Loops • Loops are generally used for repetition of a section of code • There are three basic types: • while, for, and do-while • while and for are pretest (entrance controlled) • do-while is posttest (exit controlled) The Ohio State University

50. Common Programming Errors (1) • Use == when comparing for equivalence in while, for, and do-while statements! • (Same as using == in if-statements) • Precision problem: double x, y; . . . “while (x != y)” may always be true even though mathematically x should equal y The Ohio State University