Unit 7. 'while' Loops

Similar documents
1 Unit 8 'for' Loops

Programming Language. Control Structures: Repetition (while) Eng. Anis Nazer Second Semester

CS 103 Lecture 3 Slides

Why Is Repetition Needed?

Computer Programming. Basic Control Flow - Loops. Adapted from C++ for Everyone and Big C++ by Cay Horstmann, John Wiley & Sons

REPETITION CONTROL STRUCTURE LOGO

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

1) What of the following sets of values for A, B, C, and D would cause the string "one" to be printed?

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Programming Language. Functions. Eng. Anis Nazer First Semester

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Increment and the While. Class 15

What is Iteration? CMPT-101. Recursion. Understanding Recursion. The Function Header and Documentation. Recursively Adding Numbers

Loops! Loops! Loops! Lecture 5 COP 3014 Fall September 25, 2017

CSCE 206: Structured Programming in C++

do { statements } while (condition);

In this chapter you will learn:

Introduction to Programming I COS1511 School of Computing Revision Notes

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Chapter 3. More Flow of Control

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Chapter 5: Control Structures II (Repetition) Objectives (cont d.) Objectives. while Looping (Repetition) Structure. Why Is Repetition Needed?

Score score < score < score < 65 Score < 50

Design and Debug: Essen.al Concepts Numerical Conversions CS 16: Solving Problems with Computers Lecture #7

These are notes for the third lecture; if statements and loops.

VARIABLES & ASSIGNMENTS

C++ Programming: From Problem Analysis to Program Design, Third Edition

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

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

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

C++ Programming: From Problem Analysis to Program Design, Third Edition

The following expression causes a divide by zero error:

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

LECTURE 5 Control Structures Part 2

CSci 1113 Midterm 1. Name: Student ID:

o Counter and sentinel controlled loops o Formatting output o Type casting o Top-down, stepwise refinement

Information Science 1

Compiling with Multiple Files The Importance of Debugging CS 16: Solving Problems with Computers I Lecture #7

CSc Introduc/on to Compu/ng. Lecture 8 Edgardo Molina Fall 2011 City College of New York

Lab # 02. Basic Elements of C++ _ Part1

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Text Input and Conditionals

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

The for Loop. Lesson 11

Getting started with C++ (Part 2)

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Introduction to Programming

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Islamic University of Gaza Computer Engineering Dept. C++ Programming. For Industrial And Electrical Engineering By Instructor: Ruba A.

*Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* COMPUTER PROGRAMMING LECTURE 05 LOOPS IMRAN IHSAN

Chapter 5: Control Structures II (Repetition)

LAB 4.1 Relational Operators and the if Statement

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Understanding main() function Input/Output Streams

Exceptions, Case Study-Exception handling in C++.

CSCE 121 ENGR 112 List of Topics for Exam 1

Unit 6. Thinking with Functions

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Chapter 1 INTRODUCTION

Statements execute in sequence, one after the other, such as the following solution for a quadratic equation:

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

Information Science 1

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Lecture 7: General Loops (Chapter 7)

Solving Problems Flow Control in C++ CS 16: Solving Problems with Computers I Lecture #3

Programming - 1. Computer Science Department 011COMP-3 لغة البرمجة 1 لطالب كلية الحاسب اآللي ونظم المعلومات 011 عال- 3

Control Structures: The IF statement!

Your first C++ program

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

PIC 10A Flow control. Ernest Ryu UCLA Mathematics

Intro. Scheme Basics. scm> 5 5. scm>

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

COMP322 - Introduction to C++ Lecture 01 - Introduction

C++ for Everyone, 2e, Cay Horstmann, Copyright 2012 John Wiley and Sons, Inc. All rights reserved. Using a Debugger WE5.

LAB: WHILE LOOPS IN C++

Scientific Computing

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CS 101 Computer Programming and utilization. Dr Deepak B Phatak Subrao Nilekani Chair Professor Department of CSE, Kanwal Rekhi Building IIT Bombay

Chapter 4 - Notes Control Structures I (Selection)

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. The Increment and Decrement Operators

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Using the Command Line

BITG 1223: Selection Control Structure by: ZARITA (FTMK) LECTURE 4 (Sem 1, 16/17)

CSC128 FUNDAMENTALS OF COMPUTER PROBLEM SOLVING Chapter 4: Repetition Control Structure

Other operators. Some times a simple comparison is not enough to determine if our criteria has been met.

6.1. Chapter 6: What Is A Function? Why Functions? Introduction to Functions

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

C++ Programming Lecture 7 Control Structure I (Repetition) Part I

conditional statements

Transcription:

1 Unit 7 'while' Loops

2 Control Structures We need ways of making decisions in our program To repeat code until we want it to stop To only execute certain code if a condition is true To execute one segment of code or another Language constructs that allow us to make decisions are referred to as control structures The common ones are: if statements switch statements while loops for loops

3 Loops Loops are structures of code that may be repeated some number of times Examples: Sum each student's grades (for all students in the class) Search through a sequence of numbers for a particular value Attend lecture We need some condition to tell us when to stop looping, otherwise we'll repeat our code forever and never stop (a.k.a. an infinite loop) Several kinds of loops: 'while', 'do..while', and 'for' We will focus on 'while' and 'do..while' in this unit

4 Why We Need Loops (1) Suppose we are writing a program for a simple turn-based guessing game where the user must guess a secret number If they guess incorrectly what should we do? #include <iostream> using namespace std; int main() int guess; int secretnum = /* some code */ if(guess!= secretnum) /* What should we do here? */ else return 0;

5 Why We Need Loops (2) What if they guess wrong a second time? What should we do? #include <iostream> using namespace std; int main() int guess; int secretnum = /* some code */ if(guess!= secretnum) if(guess!= secretnum) /* What should we do here? */ else else return 0;

6 Why We Need Loops (2) We can never write enough if statements because someone might always use one more turn than we have if statements But we see there is a repetitive structure in this code Let's use a loop #include <iostream> using namespace std; int main() int guess; int secretnum = /* some code */ if(guess!= secretnum) if(guess!= secretnum) if(guess!= secretnum) /* What should we do here? */ else cout << "You got it!"<< endl; else else

7 while Loops A while loop is essentially a repeating 'if' statement if (condition) // executed if condition1 is true // following statements while (condition) // executed if condition1 is true // go to top, eval cond1 again // following statements // only gets here when cond1 is false condition False condition False True If Block Statements True while Block Statements Following statements Following statements

8 while Loops A while loop is essentially a repeating 'if' statement Condition: T 1 2 T F 3 5 4 while (condition) // executed if condition1 is true // go to top, eval cond1 again 6 // following statements // only gets here when cond1 is false condition False True while Block Statements Following statements

9 When Do I Use a While Loop (1) When you don't know in advance how many times something should repeat? How many guesses will the user need before they get it right? #include <iostream> using namespace std; int main() int guess; int secretnum = /* some code */ while(guess!= secretnum) cout << "Enter guess: " << endl; return 0;

10 When Do I Use a While Loop (2) Whenever you see or use the word 'until' in a description Important Tip: "until" = "while not" Saying "keep guessing until you are correct" is the same as "keep guessing while you are not correct" #include <iostream> using namespace std; int main() int guess; int secretnum = /* some code */ while(guess!= secretnum) cout << "Enter guess: " << endl; return 0;

11 What Goes In an while Block What do we put in an while loop? ANYTHING! Expressions & variable assignment Function calls Even other if..else statements #include <iostream> using namespace std; int main() int guess; int secretnum = /* some code */ while(guess!= secretnum) cout << "Enter guess: " << endl; return 0;

12 What Goes In an while Condition What do we put in a while condition? ANYTHING. The compiler will interpret what is in the parentheses as a Boolean 0 = false Non-0 = true int main() int x, y, val; bool done; // Uses Boolean result of comparison while( x > 0 ) /* code */ // Uses value of bool variable. // Executes if done == false. while(!done ) /* code */ // Interprets number as a bool // Executes if val is non-zero while( val ) /* code */ // Interprets return value as bool // Executes if the min is non-zero while( min(x,y) ) /* code */ return 0;

13 Hand Tracing (1) Trace through the code and show all changes to x and y for: x = 24 y = 18 int main() int x, y; cin >> x; while( (x % 2) == 0) x = x/2; cin >> y; while(y > 0) if( y >= 10 ) y -= 5; else if( y >= 5 ) y -= 3; else y -= 1; return 0;

14 Hand Tracing (2) Trace through the code and show all changes to x and y for: x = 27 y = 6 int main() int x, y; cin >> x; while( (x % 2) == 0) x = x/2; cin >> y; while(y > 0) if( y >= 10 ) y -= 5; else if( y >= 5 ) y -= 3; else y -= 1; return 0;

15 Exercises 1 cpp/while/whilen cpp/while/sum50 cpp/while/blastoff

16 do..while Loops (1) while loops have a sibling known as do..while loops do..while loops Start with keyword do Followed by the body of code to be executed repeatedly in brackets Ends with while condition and semicolon (;) do..while loops will execute the body at least once int main() int x, y, val; bool quit; // a while loop while( x < val ) /* body of code */ // a do..while loop do /* body of code */ while( x < val ); return 0;

17 do..while Loops (2) do..while loops check the condition after executing at least once and repeat if the condition is true while (condition) // executed if condition1 is true // go to top, eval cond1 again // following statements // only gets here when cond1 is false do // executed at least once while (condition);// go to 'do' (top) //if cond1 evals to true // following statements // only gets here when cond1 is false condition True False True while Block Statements while Block Statements condition False Following statements Following statements

18 do..while Loops (3) do..while loops check the condition after executing at least once and repeat if the condition is true 1 3 4 Condition: T 2 T F 6 5 7 do // executed at least once while (condition);// go to 'do' (top) //if cond1 evals to true // following statements // only gets here when cond1 is false True while Block Statements condition False Following statements

19 When Should I Use do..while We generally prefer while loops We can use do..while loops when we know we want to execute the code at least one time (and then check at the end) Even then See next slide

20 Converting do..while to while Loops do while (guess!= secretnum); while (guess!= secretnum) // go to top, eval cond1 again We need to get one guess at least and then determine if we should repeat. This seems a natural fit for the do..while structure but we can easily mimic this behavior with a normal while loop. We can duplicate the body of the loop once before we start the loop. guess = secretnum + 1; while (guess!= secretnum) // go to top, eval cond1 again We can set our variables to ensure the while condition is true the first time.

21 Exercises 2 cpp/while/dowhilen cpp/while/goldilocks

22 Common Loop Mistakes Failing to update the variables that affect the condition Assignment rather than equality check Off by one error Often leads to infinite loops When you run your program it will not stop Use Ctrl+c to force quit it int i=0, n=10; while (i < n) cout << "Iteration " << i << endl; // Oops forgot to change i cout << "Done" << endl; int i=0, n=5; while (i = n) // oops, meant i==n cin >> i; cout << "Done" << endl; int i=0; // want to print "Hi" 5 times while (i <= 5) // oops, meant i < n cout << "Hi" << endl; i++;

23 Flags: A Common while Structure A Boolean flag Two values: true or false Pattern: Initialize to a value that will cause the while loop to be true the first time and then check for the ending condition in an if statement and update the flag Up to you to determine the meaning of the flag (e.g. done or again) int guess, secretnum; bool done = false; while (! done ) if(guess == secretnum) done = true; int guess, secretnum; bool again = true; while ( again ) if(guess == secretnum) again = false;