CSE1222: Lecture 7The Ohio State University1
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; } CSE1222: Lecture 7The Ohio State University2
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) = log(3) = log(4) = log(5) = log(6) = log(7) = log(8) = CSE1222: Lecture 7The Ohio State University3
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 CSE1222: Lecture 7The Ohio State University4
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; } CSE1222: Lecture 7The Ohio State University5
logWhile.cpp... k = 1; while (k <= 8) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; }... > logWhile.exe log(1) = 0 log(2) = log(3) = log(4) = log(5) = log(6) = log(7) = log(8) = CSE1222: Lecture 7The Ohio State University6
while Loops The while statement syntax: while (conditional expression) { statement1; statement2;... } CSE1222: Lecture 7The Ohio State University7
How while Loops Work 1. First test the conditional expression If it is true, then execute the statement(s) within the loop structure is/are executed 2. 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 3. If the condition ever evaluates to false, then stop the while statement; the program continues execution after the while statement CSE1222: Lecture 7The Ohio State University8
Control Flow of a while Loop CSE1222: Lecture 7The Ohio State University9
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 CSE1222: Lecture 7The Ohio State University10
While Example count = 1; while (count <= 10) { cout << count << “ “; count++;//increment count! } Output is “ ” 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 CSE1222: Lecture 7The Ohio State University11
Control Flow of the Example Program CSE1222: Lecture 7The Ohio State University12
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 CSE1222: Lecture 7The Ohio State University13
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; } CSE1222: Lecture 7The Ohio State University14
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) = log(3) = log(4) = log(5) = CSE1222: Lecture 7The Ohio State University15
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 ??? CSE1222: Lecture 7The Ohio State University16
Repetition Structures 3 If a program receives incorrect input, it can repeatedly prompt for the correct input CSE1222: Lecture 7The Ohio State University17
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; } CSE1222: Lecture 7The Ohio State University18
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) = CSE1222: Lecture 7The Ohio State University19
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; } CSE1222: Lecture 7The Ohio State University20 Try running this program
probability.cpp... int main() { double p(0.0); cout << "Enter probability player A wins 1 game: "; cin >> p; while (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; } CSE1222: Lecture 7The Ohio State University21
> 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 = > CSE1222: Lecture 7The Ohio State University22... while (p 1.0) { cout << "Input must be in range [0:1]." << endl; cout << "Enter probability player A wins 1 game: "; cin >> p; }...
temperature.cpp // print a table converting fahrenheit to celsius... int fahrenheit(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 ) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE }... CSE1222: Lecture 7The Ohio State University23
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 ) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE }... > temperature.exe Enter min and max fahrenheit: farenheit = 20 celsius = farenheit = 30 celsius = farenheit = 40 celsius = farenheit = 50 celsius = 10 farenheit = 60 celsius = CSE1222: Lecture 7The Ohio State University24
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 ) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE }... > temperature.exe Enter min and max fahrenheit: farenheit = 25 celsius = farenheit = 35 celsius = farenheit = 45 celsius = farenheit = 55 celsius = CSE1222: Lecture 7The Ohio State University25
temperature2.cpp... int STEP_SIZE(5);... fahrenheit = min_fahrenheit; while (fahrenheit <= max_fahrenheit) { float celsius = (fahrenheit ) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE }... > temperature2.exe Enter min and max fahrenheit: farenheit = 25 celsius = farenheit = 30 celsius = farenheit = 35 celsius = farenheit = 40 celsius = farenheit = 45 celsius = farenheit = 50 celsius = 10 farenheit = 55 celsius = farenheit = 60 celsius = CSE1222: Lecture 7The Ohio State University26
temperatureError.cpp // print a table converting fahrenheit to celsius... int fahrenheit(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 ) * 5.0/9.0; cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE }... CSE1222: Lecture 7The Ohio State University27
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; } CSE1222: Lecture 7The Ohio State University28
CSE1222: Lecture 7The Ohio State University29
logFor.cpp // example of for loop for log(k) for k = 1,2,..,8 #include using namespace std; int main() { for (int k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; } return 0; } CSE1222: Lecture 7The Ohio State University30
logFor.cpp... for (int k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; }... > logFor.exe log(1) = 0 log(2) = log(3) = log(4) = log(5) = log(6) = log(7) = log(8) = CSE1222: Lecture 7The Ohio State University31
for Loop Syntax for (initialize; condition; alter) { statement1; statement2; statement3; statement4;... } CSE1222: Lecture 7The Ohio State University32
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 CSE1222: Lecture 7The Ohio State University33
How for Loops Work 1. First, the initialization statements are executed 2. Then the conditional expression is tested. If it is true, then the statement(s) within the loop structure is/are executed. 3. Once the end of those statements is reached, then altering statements are executed, and the process is repeated. 4. If the expression ever evaluates to false, then the loop statement is exited, and the program continues beyond the loop. CSE1222: Lecture 7The Ohio State University34
Control Flow of a for Loop CSE1222: Lecture 7The Ohio State University35
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++; } CSE1222: Lecture 7The Ohio State University36
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++; } CSE1222: Lecture 7The Ohio State University37
(Too) Clever for Loop Example double x(0.0); cout << “Enter Number: “; for (cin >> x; x > 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; CSE1222: Lecture 7The Ohio State University38
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 CSE1222: Lecture 7The Ohio State University39
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? CSE1222: Lecture 7The Ohio State University40
Using Nested Loops A loop inside of another loop Extremely useful and very common for (int i = 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? CSE1222: Lecture 7The Ohio State University41
CSE1222: Lecture 7The Ohio State University42
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 }... CSE1222: Lecture 7The Ohio State University43
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 CSE1222: Lecture 7The Ohio State University44
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 }... CSE1222: Lecture 7The Ohio State University45
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 CSE1222: Lecture 7The Ohio State University46
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 }... CSE1222: Lecture 7The Ohio State University47
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. CSE1222: Lecture 7The Ohio State University48
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) CSE1222: Lecture 7The Ohio State University49
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 CSE1222: Lecture 7The Ohio State University50
Common Programming Errors (1) For each statement, what is the output? for (int i = 1; i < 7; i++) { cout << i << endl; } for (int i = 1; i <= 7; i++) { cout << i << endl; } for (int i = 0; i <= 7; i++) { cout << i << endl; } for (int i = 0; i < 7; i++) { cout << i << endl; } CSE1222: Lecture 7The Ohio State University51
Common Programming Errors (1) For each statement, what is the output? for (int i = 1; i < 7; i++) { cout << i; } for (int i = 1; i < 7; i++) { cout << “Row “ << i; for (int j = 1; j < 4; j++) { cout << “ Col “ << j << endl; } } CSE1222: Lecture 7The Ohio State University52
Common Programming Errors (2) Do not place a semicolon at the end of a for statement: int i; for (i = 1; i <= 10; i++); { cout << “i = “ << i << endl; } What does this output? CSE1222: Lecture 7The Ohio State University53
Common Programming Errors (3) Use semicolons, not commas, to separate items in a for statement: for (i=0, i<10, i++) //invalid for (i=0; i<10; i++)//valid Do not forget the semicolon at the end of the while statement in a do-while loop do {... } while(x > 0); CSE1222: Lecture 7The Ohio State University54
CSE1222: Lecture 7The Ohio State University55
Interactive Input with a loop int main() { double x(0.0), total(0.0), average(0.0); const int NUM_INPUTS(4); total = 0.0; for (int i = 0; i < NUM_INPUTS; i++) { // ask user for a number cout << "Enter a number: "; cin >> x; total = total + x; } average = total / NUM_INPUTS; cout << "The average of the entered values is: " << average << endl; } CSE1222: Lecture 7The Ohio State University56
Selection within a Loop int main() { double x(0.0), postot(0.0), negtot(0.0); const int NUM_INPUTS(5); // NOTE: postot and negtot initialized to 0. for (int i = 1; i <= NUM_INPUTS; i++) { cout << "Enter a number: "; cin >> x; // Selection: Separate positive from negative inputs. if (x > 0) { postot = postot + x; } else { negtot = negtot + x; } } cout << "The positive total is " << postot << endl; cout << "The negative total is " << negtot << endl; return(0); } CSE1222: Lecture 7The Ohio State University57
Selection within a Loop (2) int main() { double x(0.0), postot(0.0), negtot(0.0); cout << "Enter a number: "; cin >> x; // NOTE: postot and negtot initialized to 0. while (x != 0.0) { // Selection: Separate positive from negative inputs. if (x > 0) { postot = postot + x; } else { negtot = negtot + x; } cout << "Enter a number: "; cin >> x; } cout << "The positive total is " << postot << endl; cout << "The negative total is " << negtot << endl;... CSE1222: Lecture 7The Ohio State University58
Evaluating Functions of One Variable // Calculates several values for y = 10x² + 3x - 2 int main() { int x(0), y(0), xmin(0), xmax(0); cout << "Minimum and maximum x values: "; cin >> xmin >> xmax; for (x = xmin; x <= xmax; x++) { y = 10 * pow(x, 2) + 3 * x – 2; cout << "x = " << x << " f(x) = " << y << endl; } CSE1222: Lecture 7The Ohio State University59
Prompting for Correct Input int main() { const int MAX_AGE(125); int age(0); cout << “Enter your age (1-“ << MAX_AGE << “):”; cin >> age; while (age MAX_AGE) { cout << “Invalid input. Try again.” << endl; cout << “Enter your age (1-“ << MAX_AGE << “):”; cin >> age; } CSE1222: Lecture 7The Ohio State University60
Summation: Sum of Cubes... int main() { long sum(0); int n(0); cout << “Enter number of terms in the summation: “; cin >> n; for (int i = 1; i <= n; i++) { sum += i*i*i; } cout << “1^3 + 2^3 + 3^ “ << n << “^3 = “ << sum << endl; return 0; } CSE1222: Lecture 7The Ohio State University61
Summation Over Two Variables CSE1222: Lecture 7The Ohio State University62
Summation Over Two Variables CSE1222: Lecture 7The Ohio State University63 (i-j)j=0j=1j=2j=3... i=00... i= i= i=
Summation Over Two Variables CSE1222: Lecture 7The Ohio State University64
Algorithm From “Programming and Problem Solving with C++” By Nell Dale: An algorithm is “a step-by-step procedure for solving a problem”. CSE1222: Lecture 7The Ohio State University65
Summation Over Two Variables CSE1222: Lecture 7The Ohio State University66
Summation over two variables... int main() { long sum(0); // Initialize sum to zero int n(0); cout << "Enter max value of i: "; cin >> n; for (int i = 0; i <= n; i++) { for (int j = 0; j <= i; j++) { sum = sum + (i-j); } cout << "sum_{i=0}^n sum_{j=0}^i (i-j) = " << sum << endl; return 0; } CSE1222: Lecture 7The Ohio State University67
Printing a table using nested loops Input: n Output: Table of 1/(i-j) 2 for i = 1,...,n and j = 1,...,n. Don’t print anything when i = j. Why? CSE1222: Lecture 7The Ohio State University68
Printing a table using nested loops Input: n Output: Table of 1/(i-j) 2 for i = 1,...,n and j = 1,...,n. Algorithm: 1. for i ← 1 to n do 2. for j ← 1 to n do 3. if (i ≠ j) print 1/(i-j) 2 4. else print "******" 5. print newline; (Why?) CSE1222: Lecture 7The Ohio State University69
Printing a table using nested loops... int main() { int numRows(0); int diff(0); cout << "Enter number of table rows: "; cin >> numRows; cout.setf(ios::fixed); // fixed precision output... CSE1222: Lecture 7The Ohio State University70
Printing a table using nested loops... for (int i = 1; i <= numRows; i++) { for (int j = 1; j <= numRows; j++) { if (i != j) { diff = i-j; cout << " " << 1.0/(diff*diff); } else { cout << " ****** "; } cout << endl; // end row }... CSE1222: Lecture 7The Ohio State University71
> printTable.exe Enter number of table rows: 6 ****** ****** ****** ****** ****** ****** > CSE1222: Lecture 7The Ohio State University72 for (int i = 1; i <= numRows; i++){ for (int j = 1; j <= numRows; j++) { if (i != j) { diff = i-j; cout << " " << 1.0/(diff*diff); } else { cout << " ****** "; } } cout << endl; // end row }
Problem: Print primes Print prime numbers between 2 and n. CSE1222: Lecture 7The Ohio State University73
Print prime numbers Input: n Output: Prime numbers between 2 and n. Algorithm: 1. for k ← 2 to n do 2. flag_composite ← false; 3. for j ← 2 to k-1 do 4. if (k mod j = 0) then 5. flag_composite ← true; 6. if (flag_composite = false) print k. CSE1222: Lecture 7The Ohio State University74
prime.cpp... int main() { int n(0); bool flag_composite(false); cout << "Enter n: "; cin >> n;... CSE1222: Lecture 7The Ohio State University75
prime.cpp... cout << "Prime numbers:" << endl; for (int k = 2; k <= n; k++) { flag_composite = false; for (int j = 2; j < k; j++) { if (k%j == 0) // if (k mod j == 0) { flag_composite = true; } if (!flag_composite) { cout << k << endl; // k is prime }... CSE1222: Lecture 7The Ohio State University76
> prime.exe Enter n: CSE1222: Lecture 7The Ohio State University77 for (int k = 2; k <= n; k++) { flag_composite = false; for (int j = 2; j < k; j++) { if (k%j == 0) // if (k mod j == 0) { flag_composite = true; } } if (!flag_composite) { cout << k << endl; } // k is prime }
Types of Loops More loops Pretest Loops check the looping condition first, then begins execution ○ while ○ for Posttest Loops begins execution first, then checks looping condition ○ do-while CSE1222: Lecture 7The Ohio State University78
Summary while loops: Repeat until some condition is fulfilled; Pretest loop. for loops: Used for counting; 3 parts: for (initialize; condition; alter){...} Pretest loop. do-while loops: Example: “Do you wish to continue?” Posttest loop. CSE1222: Lecture 7The Ohio State University79