The While Loop. Objectives. Textbook. WHILE Loops



Similar documents
QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

6. Control Structures

While Loop. 6. Iteration

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Chapter One Introduction to Programming

Answers to Review Questions Chapter 7

While and Do-While Loops Summer 2010 Margaret Reid-Miller

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

Chapter 5. Selection 5-1

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

ALGORITHMS AND FLOWCHARTS

Lecture 2 Notes: Flow of Control

Flowchart Techniques

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Linear Equations and Inequalities

The if Statement and Practice Problems

Moving from C++ to VBA

Informatica e Sistemi in Tempo Reale

Chapter 8 Selection 8-1

7.7 Case Study: Calculating Depreciation

Conditions & Boolean Expressions

Sources: On the Web: Slides will be available on:

F ahrenheit = 9 Celsius + 32

JavaScript: Control Statements I

Stacks. Linear data structures

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

UEE1302 (1102) F10 Introduction to Computers and Programming

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

C++ Input/Output: Streams

Passing 1D arrays to functions.

PART A: For each worker, determine that worker's marginal product of labor.

Building Java Programs

Introduction to Python

Market Supply in the Short Run

Common Beginner C++ Programming Mistakes

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

13 Classes & Objects with Constructors/Destructors

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Writing Control Structures

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Member Functions of the istream Class

Visual Logic Instructions and Assignments

C++FA 5.1 PRACTICE MID-TERM EXAM

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

ECE 3401 Lecture 7. Concurrent Statements & Sequential Statements (Process)

Linear functions Increasing Linear Functions. Decreasing Linear Functions

Basics of I/O Streams and File I/O

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Iteration CHAPTER 6. Topic Summary

VB.NET Programming Fundamentals

Ch 7-1. Object-Oriented Programming and Classes

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Basic Programming and PC Skills: Basic Programming and PC Skills:

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

2010/9/19. Binary number system. Binary numbers. Outline. Binary to decimal

LOOPS CHAPTER CHAPTER GOALS

Introduction to Java

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

COMPUTER SCIENCE 1999 (Delhi Board)

if and if-else: Part 1

Solving Problems Recursively

Test Case Design Techniques

Pseudo code Tutorial and Exercises Teacher s Version

Python Loops and String Manipulation

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Notes from Week 1: Algorithms for sequential prediction

Beginning to Program Python

TETRIX Add-On Extensions. Encoder Programming Guide (ROBOTC )

Chapter 2 Introduction to Java programming

AP Computer Science Java Subset

Data Structures Fibonacci Heaps, Amortized Analysis

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Introduction to Computers and Programming. Testing

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Programming Exercises

ALGORITHMS AND FLOWCHARTS. By Miss Reham Tufail

1 Abstract Data Types Information Hiding

Chapter 15 Functional Programming Languages

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

CS 111 Classes I 1. Software Organization View to this point:

Transcription:

Objectives The While Loop 1E3 Topic 6 To recognise when a WHILE loop is needed. To be able to predict what a given WHILE loop will do. To be able to write a correct WHILE loop. To be able to use a WHILE for handling input terminated with a sentinel. 6 While Loops 1 6 While Loops 2 Textbook This topic is covered in the first part of Chapter 5. You should now read up to the end of the Fibonacci number programming example. WHILE Loops WHILE some condition holds DO some action repeatedly WHILE there is more dessert eat a spoonful; WHILE investment has not doubled leave it for another year; WHILE notes not understood study them some more; 6 While Loops 3 6 While Loops 4 1

WHILE loops in C++ while ( condition ) action; while ( condition ) { multiple statements Note there is no ; after the condition s ) or after the closing Example Note: We will see later that this behaviour would be more suited to a FOR loop. 6 While Loops 5 6 While Loops 6 Flowchart for while Do zero or more times In <Condition> F Out T while (<Condition>) <Statement> <Statement> If the <Condition> evaluates to true, the flow of program execution exits via the T (for True) branch, flowing to the <Statement>. When the <Statement> completes, execution flow loops around to perform the whole while construct again. If the condition evaluates to false, execution flows to the Out terminal, on to the statement following the while construct. 6 While Loops 7 Note that a while loop causes the body to be executed zero or more times. From the flowchart you can see that if the condition is initially true control goes straight through, without executing statement. Later we ll look at a related construct that carries out the loop body one or more times. 6 While Loops 8 2

Infinite Loops Make sure your loop body changes the loop condition. This loop will never end: Be careful What s will this loop do? x = 1; while (x!= 12) { cout << x << \n ; x = x + 2; 6 While Loops 9 6 While Loops 10 Correct WHILE loops Initialise the condition variables countdown = 5 Test the condition countdown > 0 Modify the condition variables countdown = countdown - 1 This should generally move the condition closer to being false. Double an investment How many years will it take to double 1000 euro if the annual interest is 5%? The basic loop is while value < (2 * initial-value) add another year s interest to value But this doesn t give us a value for the number of years it takes. See doubleinvestment.cpp Exercise: Turn this into a program that reads in the initial investment and interest rate. 6 While Loops 11 6 While Loops 12 3

Quick self-test Show the output of this code if x is of type int x = 10; while ( x > 0) { cout << x << \n ; x = x 3; Show the output if the condition is changed from (x > 0) to (x < 0). Counter controlled while loops A while loop can be used to read 20 numbers, and average them printout the value of an investment for each of 35 years These are counter controlled loops. But we will prefer FOR loops for loops that are to be executed a specific number of times. 6 While Loops 13 6 While Loops 14 Counter-controlled Sentinel controlled loops We ll use these a lot so pay attention! While loops are perfect for handling sequences of input of unknown length. If a special sentinel value terminates the sequence, then we use a sentinel controlled loop. E.g. use 0 to terminate series of student numbers Use a negative number to terminate a sequence of exam results 6 While Loops 15 6 While Loops 16 4

Sentinel controlled loop Deal with the variable Sentinel controlled Exercise Add a sequence of numbers terminated by a 0. See add-sequence.cpp Alter it to get average, min and max. Test whether a sequence of numbers is all even. This involves a boolean flag to keep track of whether a non-even has been found. See testsequence.cpp 6 While Loops 17 6 While Loops 18 Flag controlled loops Number-guessing game Example 5.6 in textbook Program generates a random number between 1 and 100, and then asks the user to guess the number. Responds Guess a lower number or Guess a higher number till user enters the correct number. 6 While Loops 19 6 While Loops 20 5

Random numbers A random integer between 1 and 100 is generated using (rand() + time(0)) % 100 rand() may produce the same number each time! So add an integer based on the current time: time(0) Convert to 1..100 range by getting the remainder of dividing the random integer by 100 i.e. % 100 rand() is in cstdlib library; time() is in ctime 6 While Loops 21 Another WHILE exercise Convert your feet to centimetres program into one which asks the user if he d like to do another conversion. char answer = y ; while (answer == y ) { get and convert another length... cout << Again?(y/n): ; cin >> answer; initialise test update 6 While Loops 22 Program Style - Constants Program Style - Constants Better to use a constant 37 is used repeatedly here, but it s significance is not clear It would be easy to make a mistake entering it. 6 While Loops 23 Constants can t be updated by the program. To change a constant (e.g. to 98.7) just have to change one place. 6 While Loops 24 6

Constants Another example: const double PI = 3.1415 The name of the constant should be more meaningful than the number. It is common practice to name constants with all capitals (NORMAL_TEMP, PI) Practical 3 and more realistic variants would be a good place to use lots of constants: double TAXRATE = 0.2; PRSI = 0.25; tax = gross_wage * TAXRATE; Next The next construct we ll see is the FOR loop. FOR is another way of doing something repeatedly But usually for a predictable number of times Counter controlled loops. 6 While Loops 25 6 While Loops 26 7