Repetitive Structures

85
CSE202: Lecture 7 The Ohio State University 1 Repetitive Structures

description

Repetitive Structures. logExample.cpp. // example of log(k) for k = 1,2,..,8 . . . int main() { cout

Transcript of Repetitive Structures

Page 1: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 1

Repetitive Structures

Page 2: Repetitive Structures

CSE202: Lecture 7 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;}

Page 3: Repetitive Structures

CSE202: Lecture 7 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.exelog(1) = 0log(2) = 0.693147log(3) = 1.09861log(4) = 1.38629log(5) = 1.60944log(6) = 1.79176log(7) = 1.94591log(8) = 2.07944

Page 4: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 4

Repetition Structures (Loops)

• Motivation: Allow repetition of code (e.g., outputting from 1 to 1000 should not involve the programmer to write 1000 lines of cout statements!)

Page 5: Repetitive Structures

CSE202: Lecture 7 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;}

Page 6: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 6

logWhile.cpp... k = 1; while (k <= 8) { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; }...

> logWhile.exelog(1) = 0log(2) = 0.693147log(3) = 1.09861log(4) = 1.38629log(5) = 1.60944log(6) = 1.79176log(7) = 1.94591log(8) = 2.07944

Page 7: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 7

while Loops

• The while statement is of the form:

while (conditional expression){statement1;statement2;...

}

Page 8: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 8

How while Loops Work1. First, the conditional expression is tested. If it

is true, then the statement(s) within the loop structure is/are executed.

2. Once the end of those statements is reached, then the process is repeated.

3. If the expression ever evaluates to false, then the while statement is exited, and the program continues beyond the loop.

Page 9: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 9

Types of Loops

• Pretest Loops checks the looping condition first, then begins execution– while – for

• Posttest Loops begins execution first, then checks looping condition– do-while

Page 10: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 10

Control Flow of a while Loop

TRUE

FALSE

Statement 1

Code after loop

Code prior to loop

Return tolooping

condition

...

Condition is true?

Page 11: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 11

While Examplecount = 1;while (count <= 10){cout << count << “ “;count++; //increment count!

}

• Output is “1 2 3 4 5 6 7 8 9 10”

Page 12: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 12

Control Flow of the Example Program

TRUE

FALSE

coutcounter

Code after loop

counter = 1;

counter++

counter<= 10 ?

Page 13: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 13

Repetition Structures 2

• Motivation 2: Allow repetition of code based on input (e.g., a program should be able to output n lines of cout statements where n is a user input.)

Page 14: Repetitive Structures

CSE202: Lecture 7 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;}

Page 15: Repetitive Structures

CSE202: Lecture 7 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.exeEnter number of logarithms to compute: 5log(1) = 0log(2) = 0.693147log(3) = 1.09861log(4) = 1.38629log(5) = 1.60944

Page 16: Repetitive Structures

CSE202: Lecture 7 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.exeEnter number of logarithms to compute: -3

???

Page 17: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 17

Repetition Structures 3

• If a program receives incorrect input, it can repeatedly prompt for the correct input.

Page 18: Repetitive Structures

CSE202: Lecture 7 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;}

Page 19: Repetitive Structures

CSE202: Lecture 7 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.exeEnter number: -4.5Input must be positive.Enter number: 0Input must be positive.Enter number: 4.5log(4.5) = 1.50408

Page 20: Repetitive Structures

CSE202: Lecture 7 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.

Page 21: Repetitive Structures

CSE202: Lecture 7 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;}

Page 22: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 22

> probability.exeEnter probability player A wins: 2Input must be in range [0:1].Enter probability player A wins: -1Input must be in range [0:1].Enter probability player A wins: 0.2Probability player A loses all 5 games = 0.32768>

...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; }...

Page 23: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 23

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 - 32.0) * 5.0/9.0;

cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl;

fahrenheit += STEP_SIZE; // increment by STEP_SIZE }...

Page 24: Repetitive Structures

CSE202: Lecture 7 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.exeEnter min and max fahrenheit: 20 60farenheit = 20 celsius = -6.66667farenheit = 30 celsius = -1.11111farenheit = 40 celsius = 4.44444farenheit = 50 celsius = 10farenheit = 60 celsius = 15.5556

Page 25: Repetitive Structures

CSE202: Lecture 7 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.exeEnter min and max fahrenheit: 25 60farenheit = 25 celsius = -3.88889farenheit = 35 celsius = 1.66667farenheit = 45 celsius = 7.22222farenheit = 55 celsius = 12.7778

Page 26: Repetitive Structures

CSE202: Lecture 7 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.exeEnter min and max fahrenheit: 25 60farenheit = 25 celsius = -3.88889farenheit = 30 celsius = -1.11111farenheit = 35 celsius = 1.66667farenheit = 40 celsius = 4.44444farenheit = 45 celsius = 7.22222farenheit = 50 celsius = 10farenheit = 55 celsius = 12.7778farenheit = 60 celsius = 15.5556

Page 27: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 27

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 - 32.0) * 5.0/9.0;

cout << "farenheit = " << fahrenheit << “ celsius = " << celsius << endl; fahrenheit += STEP_SIZE; // increment by STEP_SIZE }...

Page 28: Repetitive Structures

CSE202: Lecture 7 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;}

Page 29: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 29

for Loops

Page 30: Repetitive Structures

CSE202: Lecture 7 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;}

Page 31: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 31

logFor.cpp... for (int k = 1; k <= 8; k++) { cout << "log(" << k << ") = " << log(double(k)) << endl; }...

> logFor.exelog(1) = 0log(2) = 0.693147log(3) = 1.09861log(4) = 1.38629log(5) = 1.60944log(6) = 1.79176log(7) = 1.94591log(8) = 2.07944

Page 32: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 32

for Loop Syntax

for (initialize; condition; alter){statement1;statement2;statement3;statement4;...

}

Page 33: Repetitive Structures

CSE202: Lecture 7 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.

Page 34: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 34

How for Loops Work1. 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.

Page 35: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 35

Control Flow of a for Loop

TRUE

FALSE

Statement 1

Code after loop

InitializeStatement;

Return tolooping condition

...

Altering statement;

Code prior to loop

Condition is true?

Page 36: Repetitive Structures

CSE202: Lecture 7 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++; }

Page 37: Repetitive Structures

CSE202: Lecture 7 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++; }

Page 38: Repetitive Structures

CSE202: Lecture 7 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;

Page 39: Repetitive Structures

CSE202: Lecture 7 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.

Page 40: Repetitive Structures

CSE202: Lecture 7 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?

Page 41: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 41

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?

Page 42: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 42

TRUE

TRUE

FALSE

cout“i is now..”

Code after loop

int i = 1;

i++;

int j = 1;

cout“j is now..”

j++;

FALSE

i <= 5?

j <= 4?

Page 43: Repetitive Structures

CSE202: Lecture 7 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 }...

Page 44: Repetitive Structures

CSE202: Lecture 7 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.exeEnter square edge length: 6xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Page 45: Repetitive Structures

CSE202: Lecture 7 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 }...

Page 46: Repetitive Structures

CSE202: Lecture 7 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.exeEnter diagonal length: 6x x x x x x

Page 47: Repetitive Structures

CSE202: Lecture 7 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 }...

Page 48: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 48

Repetition Structures (Loops)• Motivation:

Allow repetition of code (e.g. outputting from 0 to 1000 should not involve the programmer to write 1001 lines of cout statements!)

• Two types of loops: pretest and posttest– Pretest loops check to see if a condition is true

before starting the loop and then recheck before the loop is repeated.

– Posttest loops enter the loop immediately and checks if the condition is true afterward.

Page 49: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 49

do-while Loops

Page 50: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 50

logDoWhile.cpp// example of do-while loop for log(k) for k = 1,2,..,8. . .int main(){ int k(0);

k = 1; do { cout << "log(" << k << ") = " << log(double(k)) << endl; k++; } while (k <= 8);

return 0;}

Page 51: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 51

do-while loops

• Both while and for loops are pretest loops, the “do-while” is a posttest loop.

• A posttest loop allows the statements inside the loop to be executed once before testing any condition.

Page 52: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 52

do-while Syntaxdo //No semicolon here{statement1;statement2;statement3;...

}while (expression); //semicolon here

Page 53: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 53

Control Flow of a do-while Loop

FALSE

Statement 1

Code after loop

Statement 2

...TRUE

Code prior to loop

Condition is true?

Page 54: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 54

Examplechar c(‘n’);int x(0);do{cout << “Enter value (integer): “;cin >> x;

... //rest of the program

cout << “Do you wish to continue: “;cin >> c;

}while (c == ‘y’ || c == ‘Y’);

Page 55: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 55

break and continue• Inside any loop, break; can be used to

immediately and prematurely exit the loop.– Not to be used often because having more

than one loop exit is confusing and generally considered bad programming

• continue; is used to immediately return to the starting point of the loop without further execution of the rest of the loop contents

Page 56: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 56

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)

Page 57: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 57

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.

Page 58: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 58

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; }

Page 59: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 59

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; }

}

Page 60: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 60

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?

Page 61: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 61

Common Programming Errors (3)• Use semicolons, not commas, to separate items

in a for statement:for (i=0, i<10, i++) //invalidfor (i=0; i<10; i++) //valid

• Do not forget the semicolon at the end of the while statement in a do-while loopdo {

...} while(x > 0);

Page 62: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 62

Loop Programming Techniques

Page 63: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 63

Interactive Input with a loopint 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 numbercout << "Enter a number: ";cin >> x;

total = total + x;}

average = total / NUM_INPUTS;cout << "The average of the entered values is: "

<< average << endl;}

Page 64: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 64

Selection within a Loopint 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);}

Page 65: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 65

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;

. . .

Page 66: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 66

Evaluating Functions of One Variable

// Calculates several values for y = 10x² + 3x - 2int 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; }

}

Page 67: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 67

Prompting for Correct Inputint main(){

const int MAX_AGE(125);int age(0);

cout << “Enter your age (1-“ << MAX_AGE << “):”;cin >> age;

while (age <= 0 || age > MAX_AGE){

cout << “Invalid input. Try again.” << endl;

cout << “Enter your age (1-“ << MAX_AGE << “):”;cin >> age;

}}

Page 68: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 68

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^3 + ... + “ << n << “^3 = “ << sum << endl;

return 0;}

Page 69: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 69

Summation Over Two Variables

• Input: n• Compute

Page 70: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 70

Summation Over Two Variables

• Compute • Table of (i-j) (where j ≤ i):

(i-j) j=0 j=1 j=2 j=3 ...

i=0 0 ...

i=1 1 0 ...

i=2 2 1 0 ...

i=3 3 2 1 0 ...

... ... ... ... ... ...

Page 71: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 71

Summation Over Two Variables

Input: n

Compute Algorithm:1. sum ← 0;2. for i ← 0 to n do3. for j ← 0 to i do4. sum ← sum + (i-j);

Page 72: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 72

Algorithm

From “Programming and Problem Solving with C++” By Nell Dale:

– An algorithm is “a step-by-step procedure for solving a problem”.

Page 73: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 73

Summation Over Two Variables

Input: n

Compute Algorithm:1. sum ← 0;2. for i ← 0 to n do3. for j ← 0 to i do4. sum ← sum + (i-j);

Page 74: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 74

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;}

Page 75: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 75

Printing a table using nested loops

Input: nOutput: Table of 1/(i-j)2 for i = 1,...,n and j = 1,...,n. • Don’t print anything when i = j. Why?

Page 76: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 76

Printing a table using nested loops

Input: nOutput: Table of 1/(i-j)2 for i = 1,...,n and j = 1,...,n. Algorithm:1. for i ← 1 to n do2. for j ← 1 to n do3. if (i ≠ j) print 1/(i-j)2

4. else print "******"5. print newline; (Why?)

Page 77: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 77

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

...

Page 78: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 78

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 }...

Page 79: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 79

> printTable.exeEnter number of table rows: 6 ****** 1.000000 0.250000 0.111111 0.062500 0.040000 1.000000 ****** 1.000000 0.250000 0.111111 0.062500 0.250000 1.000000 ****** 1.000000 0.250000 0.111111 0.111111 0.250000 1.000000 ****** 1.000000 0.250000 0.062500 0.111111 0.250000 1.000000 ****** 1.000000 0.040000 0.062500 0.111111 0.250000 1.000000 ****** >

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 }

Page 80: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 80

Problem: Print primes

• Print prime numbers between 2 and n.

Page 81: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 81

Print prime numbers

Input: nOutput: Prime numbers between 2 and n.Algorithm:1. for k ← 2 to n do2. flag_composite ← false;3. for j ← 2 to k-1 do4. if (k mod j = 0) then 5. flag_composite ← true;6. if (flag_composite = false) print k.

Page 82: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 82

prime.cpp...int main(){ int n(0); bool flag_composite(false);

cout << "Enter n: "; cin >> n;...

Page 83: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 83

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 } }...

Page 84: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 84

> prime.exeEnter n: 20235711131719

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 }

Page 85: Repetitive Structures

CSE202: Lecture 7 The Ohio State University 85

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.