Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.

Slides:



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

Basic Control Structures Control order of execution of statements sequential selection iteration - Repeat some action while a certain condition is true.
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.
1 9/29/06CS150 Introduction to Computer Science 1 Loops Section Page 255.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
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.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
True or False: Boolean Expression Boolean expression are expressions which evaluate to "true" or "false“ Primary operators to combine expressions: && (and),
Chapter 4: Looping. Resource: Starting Out with C++, Third Edition, Tony Gaddis 5.1 The Increment and Decrement Operators ++ and -- are operators that.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
CONTROLLING PROGRAM FLOW
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.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
 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.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
1 Do-While Statement Is a looping control structure in which the loop condition is tested after each iteration of the loop. SYNTAX do { Statement } while.
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 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
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.
CSIS 113A Lecture 5 Random Numbers, while, do-while.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Chapter 6 Looping CS185/09 - Introduction to Programming Caldwell College.
1 Three C++ Looping Statements Chapter 7 CSIS 10A.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
Control Structures RepetitionorIterationorLooping Part I.
Overview Go over parts of quiz? Another iteration structure for loop.
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
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.
A loop is a repetition control structure. body - statements to be repeated control statement - decides whether another repetition needs to be made leading.
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.
Looping ROBERT REVAES. Logical Operators  && AND  Both have to be true for it to evaluate to be true.  || OR  One or the other has to be true for.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
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.
C++ Programming: CS102 LOOP. Not everything that can be counted counts, and not every thing that counts can be counted. −Albert Einstein Who can control.
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.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Introduction to Computer Programming
Topic 4: Looping Statements
REPETITION CONTROL STRUCTURE
Chapter 5: Control Structures II (Repetition)
Lecture 6 Repetition Richard Gesick.
While Loops.
Iteration with While You can say that again.
Loops A loop is a repetition control structure.
Repetition Control Structure
Logical Operators and While Loops
Repetition Statements (Loops) - 2
Presentation transcript:

Lecture 4 Looping

Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using if statements

Advantages of Computers Computers are really quick Computers don't get bored  They can do the same thing over and over and be “happy”

Loops What is the effect of a loop? { some C++ code; } as long as some condition is true

While loops while ( num < 10 ) { cout << “num = ” << num << endl; num = num + 1; } False Bool Exp True Code Block

While loops while ( num < 10 ) cout << “Hello there \n” ; As before if there is only one line in the body of the loop, the { } are not needed. But....what is the problem? False Bool Exp Code Block True

While loops while ( num < 10 ) cout << “Hello there \n” ; As before if there is only one line in the body of the loop, the { } are not needed. But....what is the problem? Infinite Loop: a loop that doesn't end False Bool Exp Code Block True

What is a difference between if and while Which of the following is the if (left or right)? False Bool Exp Code Block True False Bool Exp Code Block True

What is a difference between if and while Which of the following is the if (left or right)? False Bool Exp Code Block True False Bool Exp Code Block True if while

Class Exercise ask the user for 10 integers return to the user the total of the 10 integers and their average Please enter 10 numbers num 1: 23 num 2: num 10: -34 The total of your 10 numbers is: 345 The average for the 10 numbers is: 34 Things to think about: What part needs to be repeated? This will go in the loop body How many variables do you need?

Answer int num = 1, total = 0, temp; cout << “Please enter 10 numbers \n” while ( num <= 10 ) { cout << “num “ << num << “:” ; cin >> temp ; total = total + temp; num = num + 1; } cout << “The total of your 10 numbers is: “ << total << endl; cout << “The average of your 10 number is: << ( total / 10 ) << endl;

Counter Controled Loop Counter Controled Loop uses a variable (num) to count and control when the loop stops int num = 1, total = 0, temp; cout << “Please enter 10 numbers \n” while ( num <=10 ) { cout << “num “ << num << “:” ; cin >> temp ; total = total + temp; num = num + 1; } cout << “The total of your 10 numbers is: “ << total << endl;

Another Class Exercise Most of the time our DOS screen is 80 characters wide To help with making a “pretty” display, make a loop that will print 80 numbers across the screen.....but always print from 1 to 10 ( 0 will represent a 10)

Answer int count = 1, output = 1; while ( count <= 80 ) { cout << output ; count = count + 1; output = output + 1; if (output > 9 )// reset output to 0 if over 9 output = 0; }

Another Answer int count = 1, output = 1; while ( count <= 80 ) { cout << output ; count = count + 1; // reset output to 0 if over 9 output = ( output > 9 ? 0 : output + 1 ); }

Another Answer int num = 1 ; while ( num <= 80 ) { cout << ( num % 10 ) ; num = num + 1; }

While loops You can put any kind of code in the code block..... False Bool Exp Code Block True

While loops You can put any kind of code in the code block even other loops False Bool Exp Code Block True False Bool Exp Code Block True

False Bool Exp Code Block True False Bool Exp Code Block True In everyday life we have an embedded loop: ???? Embedded loops (a loop inside of another loop)‏

False Bool Exp Code Block True False Bool Exp Code Block True hours minutes In everyday life we have an embedded loop: Time Embedded loops (a loop inside of another loop)‏

Creating Some Time Output int hour = 0, min; while ( hour < 24 ) { min = 0; while ( min < 60 ) { cout << hour << ':' << min << endl; min = min + 1; }// end of minute loop hour = hour + 1; }// end of hour loop

Now What is the Output? int hour = 0, min; while ( hour < 24 ) { min = 0; while ( min < 60 ) { cout << (hour < 10 ? '0' : “” ) << hour; cout << ':' ; cout << (min < 10 ? '0' : “” ) << min << endl; min = min + 1; }// end of minute loop hour = hour + 1; }// end of hour loop

Infinite loops Common Infinite Loops while ( ch = ‘y’ ) {.... } Remember: non-zero numbers  true zero  false

Infinite loops )‏ Common Infinite Loops while ( ch = ‘y’ ) {.... } Remember: non-zero numbers  true zero  false or int i = 0 while ( i < 10 ) { // forgot i++; }

Looping Control Structures Three different commands while statement do-while statement......

The Do-While Statement Syntax do code block while (bool expr); Bool Exp Code Block True False

Using a do while loop char reply; do { // some code cout > reply; } while(reply == 'y');

Why use a ? What is the advantage of a while: do...while:

Why use a ? What is the advantage of a while: body will execute 0 – N times do...while:body will execute 1 – N times

Looping Control Structures Three different commands while statement do-while statement for statement

Common use of loop int cnt = 0;// initialize while ( cnt < 10 ) {// check......; // do something body of loop......; cnt++;// update }

The for loop Syntax for (initialization ; bool expression ; update action)‏ body of the loop Example for (int i = 0; i < 3; i++) { cout << "i is " << i << endl; }

Bool Exp Body true false Initialization Update Action Executed once at the beginning of the for loop's execution The Bool Exp is evaluated at the start of each iteration of the loop

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 0

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 0

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 0 i is 0

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 0 i is 0

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 1 i is 0

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 1 i is 0

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 1 i is 0 i is 1

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 1 i is 0 i is 1

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 2 i is 0 i is 1

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 2 i is 0 i is 1

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 2 i is 0 i is 1 i is 2

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 2 i is 0 i is 1 i is 2

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 3 i is 0 i is 1 i is 2

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 3 i is 0 i is 1 i is 2

Execution Example for (int i = 0; i < 3; ++i) { cout << "i is " << i << endl; } cout << "all done" << endl; i 3 i is 0 i is 1 i is 2 all done

Embedding for loops Just like while loops, for loops can also be embedded inside other loops in fact, due to there compactness (information being easier to read) many embedded loops will be for loops

int cntr1 =0, cntr2 =0, cntr3 =0,cntr4 =0, cntr5 =0; cntr1++; for (int i = 1; i <= 10; ++i) { cntr2++; for (int j = 1; j <= 20; ++j) { cntr3++; } cntr4++; } cntr5++; cout << “cntr1: “ << cntr1 << endl << “cntr2: “ << cntr2 << endl << “cntr3: “ << cntr3 << endl << “cntr4: “ << cntr4 << endl << “cntr5: “ << cntr5 << endl; What is the output?

Answer: cntr1: 1 cntr2: 10 cntr3: 200 cntr4: 10 cntr5: 1 Press any key to continue

Class Exercise Write code to display a grid.  For each position, display the location’s row and column number. Put two blanks between each location. Ex: 1,1 1,2 1, ,9 2,1 2, , ,1 8, ,9 9,1 9,2 9, ,9

One solution to grid exercise for(int row = 1; row < 10; row++ ){ for(int col = 1; col < 10; col++) { cout << row << ‘,’ << col << “ “; }// end of col loop cout << endl; } // end of row loop

Another use of break break can be used to exit a loop // in some game while ( life > 0 ) { // play game cout << “Do you want to quit(q):”; cin >> userResponse; if (userResponse == ‘q’ )‏ break; } // end while loop not the best example

A better solution // in some game userResponse = ‘c’; while ( life > 0 && userResponse != ‘q’ ) { // play game.... cin >> userResponse; } // end while loop

The best solution // in some game do { // play game.... cin >> userResponse; } while ( life > 0 && userResponse != ‘q’ );

Another use of break break will only exit out of one loop (if embedded)‏ for ( int row = 1; row < 10; row++ ) { for ( int col = 1; col < 10; col++) { // do something if ( ???? )‏ break;// this will stop the col loop } // col loop } // row loop

Continue, the brother of break the key word, continue, will cause execution to skip to the boolean expression while( something == true ) { // do something if ( x > 0 )‏ continue;// skip to end of block // do some more.... } // end of while

Continue, the brother of break the key word, continue, will cause execution to skip to the boolean expression while( something == true ) { // do something if ( x > 0 )‏ continue;// skip to end of block // do some more.... } // end of while

Using break and continue in loops First look for a solution that does not use break or continue  Only use break and continue if it is the only solution or it makes the code easier to understand Note: always avoid using goto.... there is almost always a better way

Sentinel Controled Loops Continue doing the loop until a special value (the sentinel) is encounter

Sentinel Controled Loops Continue doing the loop until a special value (the sentinel) is encounter Example: Before we asked the user for 10 numbers and then we told the user  total of the 10 numbers  average of the 10 numbers

Sentinel Controled Loops Continue doing the loop until a special value (the sentinel) is encounter Example: Before we asked the user for 10 numbers and then we told the user  total of the 10 numbers  average of the 10 numbers Now we want the user to enter as many numbers as they want  a negative number is the signal that they are done ( the sentinel )‏

quiz int count = 1, total = 0, input = 0; cout << “Please enter some positive numbers that I will average \n”; cout << “Enter a negative number to signal that you are done \n”; while ( input >= 0 ) { cout << “# “ << count << “:” ; cin >> input; total = total + input; count = count + 1; } count = count – 1; if ( count > 0 ) { cout << “The total of your “ << count ; cout << “ numbers is: “ << total << endl; cout << “The average of your “ << count cout << “ number is: << ( total / count ) << endl; } try it with: 5 7 try it with: 5 7 Will this work?