Repetitive Structures

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
1 10/20/08CS150 Introduction to Computer Science 1 do/while and Nested Loops Section 5.5 & 5.11.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Objectives You should be able to describe:
Chapter 5: Repetition Statements. In this chapter, you will learn about: Basic loop structures while loops Interactive while loops for loops Loop programming.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Chapter 8 Repetition Statements. Introduction Iteration - process of looping or the repetition of one or more statements Loop body - the statement, or.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Control Structures RepetitionorIterationorLooping Part I.
Overview Go over parts of quiz? Another iteration structure for loop.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: The while Statement cin within a while Loop The for.
A FIRST BOOK OF C++ CHAPTER 5 REPETITION. OBJECTIVES In this chapter, you will learn about: The while Statement Interactive while Loops The for Statement.
A First Book of C++ Chapter 5 Repetition.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter 5 Repetition. 2 Objectives You should be able to describe: The while Statement cin within a while Loop The for Statement The do Statement Common.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Computer Programming -1-
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
The Ohio State University
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Unit 3 Lesson 9 Repetition Statements (Loops)
Bill Tucker Austin Community College COSC 1315
Lecture 7: Repeating a Known Number of Times
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 07 More Repetition Richard Gesick.
Lecture 4B More Repetition Richard Gesick
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Chapter 8 Repetition Statements
Control Structure Senior Lecturer
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Outline Altering flow of control Boolean expressions
Additional Control Structures
A First Book of ANSI C Fourth Edition
Chapter 6: Repetition Statements
Computing Fundamentals
Looping III (do … while statement)
Control Structures Repetition or Iteration Looping Part I.
Alternate Version of STARTING OUT WITH C++ 4th Edition
2.6 The if/else Selection Structure
Objectives You should be able to describe: The while Statement
Repetition Statements (Loops) - 2
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Chapter 4 Repetition Structures
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Repetitive Structures CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

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!) CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

The Ohio State University while Loops The while statement is of the form: while (conditional expression) { statement1; statement2; ... } CSE1222: Lecture 7 The Ohio State University

The Ohio State University How while Loops Work First, 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 the process is repeated. If the expression ever evaluates to false, then the while statement is exited, and the program continues beyond the loop. CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

Control Flow of a while Loop CSE1222: Lecture 7 The Ohio State University

The Ohio State University While Example count = 1; while (count <= 10) { cout << count << “ “; count++; //increment count! } Output is “1 2 3 4 5 6 7 8 9 10” CSE1222: Lecture 7 The Ohio State University

Control Flow of the Example Program CSE1222: Lecture 7 The Ohio State University

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.) CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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; Note: Header deleted in slide CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

Repetition Structures 3 If a program receives incorrect input, it can repeatedly prompt for the correct input. CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 << "log(" << x << ") = “ << log(x) << endl; return 0; CSE1222: Lecture 7 The Ohio State University

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

The Ohio State University 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. CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 << "Probability player A loses all 5 games = " << pow((1-p), 5.0) << endl; return 0; CSE1222: Lecture 7 The Ohio State University

The Ohio State University ... 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 Enter probability player A wins: 0.2 Probability player A loses all 5 games = 0.32768 > CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 } CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 } Try 20, 60. Try 0, 100. Try 25, 75. Try 20, 75. CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

The Ohio State University for Loops CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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; CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 CSE1222: Lecture 7 The Ohio State University

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

The Ohio State University 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 7 The Ohio State University

The Ohio State University 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. CSE1222: Lecture 7 The Ohio State University

Control Flow of a for Loop CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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) k++; CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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) k++; CSE1222: Lecture 7 The Ohio State University

(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: cout << “Enter number: “; cin >> x; while (x <= 0) cout << "log(" << x << ") = " << log(x) << endl; CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

The Ohio State University 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 << k << endl; // What is the value of k? CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

The Ohio State University CSE1222: Lecture 7 The Ohio State University

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 7 The Ohio State University

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 7 The Ohio State University

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 7 The Ohio State University

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 7 The Ohio State University

The Ohio State University 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 Will this program compile? What will it output when it runs? CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

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 7 The Ohio State University

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++) for (int i = 0; i <= 7; i++) for (int i = 0; i < 7; i++) CSE1222: Lecture 7 The Ohio State University

Common Programming Errors (1) For each statement, what is the output? for (int i = 1; i < 7; i++) { cout << i; } { cout << “Row “ << i; for (int j = 1; j < 4; j++) { cout << “ Col “ << j << endl; } } CSE1222: Lecture 7 The Ohio State University

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? Outputs: i = 11 CSE1222: Lecture 7 The Ohio State University

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 7 The Ohio State University

Loop Programming Techniques CSE1222: Lecture 7 The Ohio State University

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 7 The Ohio State University

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 7 The Ohio State University

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 << "The positive total is " << postot << endl; cout << "The negative total is " << negtot << endl; . . . CSE1222: Lecture 7 The Ohio State University

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 7 The Ohio State University

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 <= 0 || age > MAX_AGE) cout << “Invalid input. Try again.” << endl; } CSE1222: Lecture 7 The Ohio State University

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; CSE1222: Lecture 7 The Ohio State University

Summation Over Two Variables Input: n Compute 𝑖=0 𝑛 𝑗=0 𝑖 𝑖−𝑗 . Outputs: i = 11 CSE1222: Lecture 7 The Ohio State University

Summation Over Two Variables Compute 𝑖=0 𝑛 𝑗=0 𝑖 𝑖−𝑗 . Table of (i-j) (where j ≤ i): (i-j) j=0 j=1 j=2 j=3 ... i=0 i=1 1 i=2 2 i=3 3 Outputs: i = 11 CSE1222: Lecture 7 The Ohio State University

Summation Over Two Variables Input: n Compute 𝑖=0 𝑛 𝑗=0 𝑖 𝑖−𝑗 . Algorithm: sum ← 0; for i ← 0 to n do for j ← 0 to i do sum ← sum + (i-j); Outputs: i = 11 CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

Summation Over Two Variables Input: n Compute 𝑖=0 𝑛 𝑗=0 𝑖 𝑖−𝑗 . Algorithm: sum ← 0; for i ← 0 to n do for j ← 0 to i do sum ← sum + (i-j); Outputs: i = 11 CSE1222: Lecture 7 The Ohio State University

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 7 The Ohio State University

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 7 The Ohio State University

Printing a table using nested loops Input: n Output: Table of 1/(i-j)2 for i = 1,...,n and j = 1,...,n. Algorithm: for i ← 1 to n do for j ← 1 to n do if (i ≠ j) print 1/(i-j)2 else print "******" print newline; (Why?) CSE1222: Lecture 7 The Ohio State University

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 7 The Ohio State University

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 7 The Ohio State University

The Ohio State University 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 > printTable.exe Enter 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 ****** > CSE1222: Lecture 7 The Ohio State University

The Ohio State University Problem: Print primes Print prime numbers between 2 and n. CSE1222: Lecture 7 The Ohio State University

The Ohio State University Print prime numbers Input: n Output: Prime numbers between 2 and n. Algorithm: for k ← 2 to n do flag_composite ← false; for j ← 2 to k-1 do if (k mod j = 0) then flag_composite ← true; if (flag_composite = false) print k. CSE1222: Lecture 7 The Ohio State University

The Ohio State University prime.cpp ... int main() { int n(0); bool flag_composite(false); cout << "Enter n: "; cin >> n; CSE1222: Lecture 7 The Ohio State University

The Ohio State University 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 7 The Ohio State University

The Ohio State University 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 > prime.exe Enter n: 20 2 3 5 7 11 13 17 19 CSE1222: Lecture 7 The Ohio State University

The Ohio State University Summary while loops: Repeat until some condition is fulfilled; Pretest loop. for loops: Used for counting; 3 parts: for (initialize; condition; alter){...} do-while loops: Example: “Do you wish to continue?” Posttest loop. CSE1222: Lecture 7 The Ohio State University