Programming Loops (continued).

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Computer Science 1620 Loops.
Iterative Constructs – chapter 4 pp 189 to 216 This lecture covers the mechanisms for deciding the conditions to repeat action. Some materials are from.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Control Constructs Mechanisms for deciding when and how often an action should be taken.
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.
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.
Loops. COMP104 Loops / Slide 2 Shortcut Assignment * C++ has a set of operators for applying an operation to a variable and then storing the result back.
Structured Programming Programming. COMP102 Prog Fundamentals I: Structured Programming /Slide 2 Structured Programming l Structured programing is the.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated JPC and JWD © 2002 McGraw-Hill, Inc.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
For Loops Programming. COMP102 Prog Fundamentals I: for Loops/Slide 2 The for Statement condition action true false initialization update.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
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.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
Algorithms JPC and JWD © 2002 McGraw-Hill, Inc. 2 Algorithms 2 An Algorithm is a finite set of precise instructions for performing a computation or for.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
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.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
C++ Iterative Constructs
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
CS161 Introduction to Computer Science
Branching Constructs Review
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
Repetition-Sentinel,Flag Loop/Do_While
Chapter 2.2 Control Structures (Iteration)
Programming Fundamentals
JavaScript: Control Statements.
Lecture 4B More Repetition Richard Gesick
Chapter 8 Repetition Statements
Conditinoal Constructs Review
COMS 261 Computer Science I
Outline Altering flow of control Boolean expressions
Loops (iterations, repetitions)
Conditinoal Constructs Review
Counting Loops.
Miscellaneous Flow Control
Chapter 2.2 Control Structures (Iteration)
Computing Fundamentals
Chapter 5: Control Structures II (Repetition)
Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated JPC and JWD © 2002 McGraw-Hill, Inc.
Loops.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

Programming Loops (continued)

The for Statement Syntax for (ForInit; ForExpression; PostExpression) Action How it works: Execute ForInit statement While ForExpression is true Execute Action Execute PostExpression Example int i; for(i=1; i<=20; i++) cout << "i is " << i << endl;

Iteration Using the for Statement ForInit ForExpression true false Action PostExpression

N! (for) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; for(n=1; n<=number; n++) factorial *= n; cout << "The factorial of " << number << " is " << factorial << endl;

2N (for) int number, result, n; cout << "Enter number: "; cin >> number; result = 1; for(n=1; n<=number; n++) result *= 2; cout << "Two raised to the " << number << " power is " << result << endl;

Iteration Key Points [stopping criterion] Make sure there is a statement that will eventually stop the loop [initialization]Make sure to initialize loop counters correctly [side effect] Loop counters should not be modified in the loop

The Lazy Student Problem Four students working together on HW1 Problem will take 200 hours of work that can be done over the next few weeks The laziest student convinces the other three students to draw straws Each straw is marked with an amount The amount represents both the number of days and the numbers of hours per day that the student would work Example If the straw was marked three then the student who drew it would work for three hours per day for three days What are the best markings of the straws for a clever, lazy student?

Observations Need to find sets of numbers a, b, c, and d such that a2 + b2 + c2 + d2 = 200 Maximal legal number is 14 as 152 equals 225 which is greater than 200 Minimal legal number is 1 No advantage to listing the combinations more than once Implication Generate the solutions systematically We will make sure that a <= b <= c <= d

Method Generate all possibilities for a where for each a possibility Generate all possibilities of b where for each b possibility Generate all possibilities for c where for each c possibility Generate all possibilities for d where for each d possibility Determine whether the current combination is a solution

Nested For Loop Solution int a, b, c, d; for(a=1; a<=14; a++) { for(b=a; b<=14; b++) { for(c=b; c<=14; c++) { for(d=c; d<=14; d++) { if(a*a + b*b + c*c + d*d == 200) cout << a << " " << b << " " << c << " " << d << endl; }

The Do-While Statement Syntax do Action while (Expression) How it works: Execute Action if Expression is true then execute Action again Repeat this process until Expression evaluates to false Action is either a single statement or a group of statements within braces Action true Expression false

N! (do-while) int number, factorial, n; cout << "Enter number: "; cin >> number; factorial = 1; n = 1; do{ factorial *= n; n++; }while(n <= number); cout << "The factorial of " << number << " is " << factorial << endl;

2N (do-while) int number, result, n; cout << "Enter number: "; cin >> number; result = 1; n = 1; do{ result *= 2; n++; }while (n <= number); cout << "Two raised to the " << number << " power is " << result << endl;

Maximum (do-while) int value; //input value int max=0; //maximum value cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; }while(value!=-1); cout << "The maximum value found is " << " is " << max << endl;

Waiting for a Reply char reply; do{ cout << "Continue(y/n): "; cin >> reply; //do something }while(reply!='n');

Which Loop to Use? For loop While loop Do-while loop Best for calculations that are repeated a fixed number of times using a value that is changed by an equal amount (usually 1) each time through the loop. While loop You want to repeat a segment of code without knowing exactly how many times it will be repeated. You are working with user input There are situations when the code segment should not be executed at all. Do-while loop The code segment should always be executed at least once. Otherwise, the situations when do-while loops are used are very similar to those when while loops are used.

A simpler lazy student problem three straws: a, b, c minimum value = 1 maximum value = 3 a <= b <= c 1 1 1 1 1 2 1 1 3 1 2 2 1 2 3 1 3 3 2 2 2 2 2 3 2 3 3 3 3 3 for (a=1; a<=3; a++) for (b=a; b<=3; b++) for (c=b; b<=3; c++) cout << a << b << c << endl;

How to Stop a Loop Known number of iterations before the loop stops (for) Test for a user-controlled condition before or after each iteration (while, do-while) Use the break command.

break The break command is the same as the one used previously in switch. break leaves the current loop immediately. It is recommended that break be used for situations where the loop needs to be terminated immediately (e.g., due to user intervention or if a fatal error occurs).

Maximum (while with break) int value=0; //input value int max=0; //maximum value while(true){ cout << "Enter a value (-1 to stop): "; cin >> value; if(value > max) max = value; if(value==-1) break; } cout << "The maximum value found is " << " is " << max << endl; MAX

Common Loop Errors while(balance != 0.0); { balance = balance - amount; } This will lead to an infinite loop! for(n=1; n<=count; n++); cout << "hello" << endl; "hello" only printed once!

Common Loop Errors (with correct indentation and curly braces) while(balance != 0.0) { ; // do nothing infinitely !! } balance = balance - amount; This will lead to an infinite loop! for(n=1; n<=count; n++) { ; // do nothing n times!! cout << "hello" << endl; "hello" only printed once!

Common Loop Errors while(balance != 0.0){ balance = balance - amount; } balance may not become equal zero due to numerical inaccuracies int power; while(power <= 1000){ cout << "Next power of N is " << power << endl; power *= n; Be sure to initialize to 0 a variable used for sums Be sure to initialize to 1 a variable used for products

Nested Loops Nested loops are loops within loops. They are similar in principle to nested if and if-else statements. Many applications require nested loops.

Nested Loops // Find the average score on 8 lab assignments int n, lastlab=8; double avg, score, tscore; char resp; do{ tscore = 0; for(n=1; n<=lastlab; n++){ cout << "Enter student’s score for lab " << n << ": "; cin >> score; tscore += score; } avg = tscore/double(lastlab); cout << "The average score is " << avg << endl; cout << "Enter another student (y/n)? "; cin >> resp; }while(resp=='y' || resp=='Y');

Diamond Pattern Print out the following diamond pattern * * * * * * * * * * * * * * * * * * * * * * * * *

Diamond Pattern Subproblem: Print out upper half: print out the upper half print out the lower half Print out upper half: row 1: print 4 spaces, 1 star; row 2: print 3 spaces, 3 stars; row 3: print 2 spaces, 5 stars; row 4: print 1 space, 7 stars; row 5: print 0 spaces, 9 stars; Algorithm Refinement: row 1: print (5-row) spaces, (2*row - 1) stars; row 2: print (5-row) spaces, (2*row - 1) stars; row 3: print (5-row) spaces, (2*row - 1) stars; row 4: print (5-row) spaces, (2*row - 1) stars; row 5: print (5-row) spaces, (2*row - 1) stars;

Diamond Pattern int row, space, star; // loop counters for(row=1; row<=5; row++){ //top half for(space=1; space<=5-row; space++) cout << " "; for(star=1; star<=2*row-1; star++) cout << "*"; cout << endl ; } for(row=4; row>=1; row--){ //bottom half

Multiplication Table // Program to output the // multiplication table int i; //Outer loop counter int j; //Inner loop counter for(i=1; i<=10; i++){ for(j=1; j<=10; j++) cout << i*j << " "; cout << endl; }