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.

Slides:



Advertisements
Similar presentations
Do-while Loops Programming. COMP102 Prog Fundamentals I: do-while Loops /Slide 2 The do-while Statement l Syntax do action while (condition) l How it.
Advertisements

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
If Statements & Relational Operators Programming.
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.
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
1 10/11/06CS150 Introduction to Computer Science 1 do/while and Nested Loops.
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.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
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.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
COMP103 - C++ Review1 Variables and Special Chars (Ch. 2, 3)
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.
CONTROLLING PROGRAM FLOW
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
 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 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
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.
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.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
GAME102 - INTRO WHILE LOOPS G. MacKay. Fundamental Control Structures  STRAIGHT LINE  CONDITIONAL  LOOPS.
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.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Loops and Files. 5.1 The Increment and Decrement Operators.
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.
Chapter 4 October 22, The If Statement Programs make decisions If(condition){ Statement(s); } Condition  boolean expression Evaluates to either.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
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.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
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.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 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)
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Programming Loops (continued).
C++ Iterative Constructs
REPETITION CONTROL STRUCTURE
Chapter 2.2 Control Structures (Iteration)
Programming Fundamentals
Conditinoal Constructs Review
COMS 261 Computer Science I
Intro to Programming Week # 4 Control Structure Lecture # 8
Loops (iterations, repetitions)
Counting Loops.
Miscellaneous Flow Control
3 Control Statements:.
Chapter 2.2 Control Structures (Iteration)
Control Structures Part 1
Iterative Constructs Mechanisms for deciding under what conditions an action should be repeated JPC and JWD © 2002 McGraw-Hill, Inc.
Presentation transcript:

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 into the variable  Shortcut assignments: *=, /=, +=, -=, %= * Examples int i = 3; i += 4; // i = i + 4 cout << i << endl; // i is now 7 double a = 3.2; a *= 2.0; // a = a * 2.0 cout << a << endl; // a is now 6.4 int change = 1265; change %= 100; // change = change % 100 cout << change << endl; // change is now 65

COMP104 Loops / Slide 3 Increment and Decrement * C++ has special operators for incrementing or decrementing an object by one * Examples int k = 4; ++k; // k=k+1 : k is 5 k++; // k=k+1 : k is 6 cout << k << endl; int i = k++; // i is 6, k is 7 cout << i << " " << k << endl; int j = ++k; // j is 8, k is 8 cout << j << " " << k << endl;

COMP104 Loops / Slide 4 Increment and Decrement * What is the difference between k++ and ++k? n ++k increments first, and the incremented value is used in the expression n k++ uses the initial value of k in the expression, and increments afterwards * Examples int a, b, c, d, k; k = 3; a = ++k;// k=4, a=4 b = --a;// a=3, b=3 c = b++;// c=3, b=4 d = c--;// d=3, c=2

COMP104 Loops / Slide 5 Iterative Constructs * Provide n Ability to control how many times a statement list is executed * Three constructs while statement for statement do-while statement

COMP104 Loops / Slide 6 The while Statement * Syntax while (Expression) Action * How it works: n If Expression is true then execute Action n Repeat this process until Expression evaluates to false * Action is either a single statement or a group of statements within braces Expression Action truefalse

COMP104 Loops / Slide 7 Iteration ( while ) while { }

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

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

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

The value of the input operation corresponds to true only if a successful extraction was made #include using namespace std; int main() { int listSize = 0; int value; double sum = 0.; double average; cout << "Provide a list of numbers (CTRL-D to stop) " << endl; while (cin >> value) { sum += value; listSize++; } if(listSize > 0){ average = sum / listSize; cout << "Average: " << average << endl; } else cout << "No list to average" << endl; return 0; }

COMP104 Loops / Slide 12 The for Statement * Syntax for ( ForInit; ForExpression; PostExpression ) Action * How it works: n Execute ForInit statement n While ForExpression is true  Execute Action  Execute PostExpression * Example int i; for(i=1; i<=20; i++) cout << "i is " << i << endl;

COMP104 Loops / Slide 13 Iteration Using the for Statement ForExpression Action truefalse ForInit PostExpression

COMP104 Loops / Slide 14 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;

COMP104 Loops / Slide 15 2 N ( 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;

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

COMP104 Loops / Slide 17 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;

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

COMP104 Loops / Slide 19 Maximum (do-while) int value;//input value int max=0;//maximum value do{ 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;

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

COMP104 Loops / Slide 21 Which Loop to Use? * For loop n Usually best for sums, products, and counting loops. * While loop n You want to repeat an action without knowing exactly how many times it will be repeated. n You are working with user input n There are situations when the action should not be executed. * Do-while loop n The action should always be executed at least once. n Otherwise, the do-while loops and while loops are used in similar situations.

COMP104 Loops / Slide 22 Iteration * Key Points n Make sure there is a statement that will eventually stop the loop n Make sure to initialize loop counters correctly n Have a clear purpose for the loop

COMP104 Loops / Slide 23 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)

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

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

COMP104 Loops / Slide 26 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.

COMP104 Loops / Slide 27 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');

COMP104 Loops / Slide 28 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; }

COMP104 Loops / Slide 29 Diamond Pattern * Print out the following diamond pattern * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

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

COMP104 Loops / Slide 31 Diamond Pattern int row, space, star; 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 for(space=1; space<=5-row; space++) cout << " "; for(star=1; star<=2*row-1; star++) cout << "*"; cout << endl ; }