While and Do-While Loops. 15-110 Summer 2010 Margaret Reid-Miller



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

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

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

Sample CSE8A midterm Multiple Choice (circle one)

While Loop. 6. Iteration

The While Loop. Objectives. Textbook. WHILE Loops

Topic 11 Scanner object, conditional execution

J a v a Quiz (Unit 3, Test 0 Practice)

Conditionals (with solutions)

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

Conditional Statements Summer 2010 Margaret Reid-Miller

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

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

Building Java Programs

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

Building Java Programs

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.

Chapter 2: Elements of Java

Building Java Programs

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Building Java Programs

Chapter 2 Introduction to Java programming

Using Files as Input/Output in Java 5.0 Applications

Building Java Programs

Iteration CHAPTER 6. Topic Summary

Introduction to Java

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Arrays. Introduction. Chapter 7

Programming Fundamentals I CS 110, Central Washington University. November 2015

LOOPS CHAPTER CHAPTER GOALS

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Java. CS 3: Computer Programming in Java

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

In this Chapter you ll learn:

Lecture 2 Notes: Flow of Control

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

Flowchart Techniques

Statements and Control Flow

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Reading Input From A File

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

AP Computer Science Java Subset

AP Computer Science Java Mr. Clausen Program 9A, 9B

AP Computer Science Static Methods, Strings, User Input

Part I. Multiple Choice Questions (2 points each):

Chapter 5. Selection 5-1

1.3 Conditionals and Loops

Introduction to Programming

- User input includes typing on the keyboard, clicking of a mouse, tapping or swiping a touch screen device, etc.

Informatica e Sistemi in Tempo Reale

Object Oriented Software Design

Example of a Java program

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Comp 248 Introduction to Programming

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Programming in Java Course Technology, a part of Cengage Learning.

Introduction to Java Lecture Notes. Ryan Dougherty

Unit 6. Loop statements

Chapter 8 Selection 8-1

CMSC 202H. ArrayList, Multidimensional Arrays

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Install Java Development Kit (JDK) 1.8

Homework/Program #5 Solutions

csci 210: Data Structures Recursion

Variables, Constants, and Data Types

AP Computer Science File Input with Scanner

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

JAVA ARRAY EXAMPLE PDF

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

Recursion and Recursive Backtracking

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Building Java Programs

COMS 4115 Programming Languages and Translators Fall 2013 Professor Edwards. Lullabyte

Chapter 3. Input and output. 3.1 The System class

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Programming in Java. What is in This Chapter? Chapter 1

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

COMPUTER SCIENCE. Paper 1 (THEORY)

6. Control Structures

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Data Structures Lecture 1

Elementary Number Theory and Methods of Proof. CSE 215, Foundations of Computer Science Stony Brook University

Program Logic to Java GEEN163

Moving from CS 61A Scheme to CS 61B Java

Stats on the TI 83 and TI 84 Calculator

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

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

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

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

10.2 Series and Convergence

Transcription:

While and Do-While Loops 15-110 Margaret Reid-Miller

Loops Within a method, we can alter the flow of control using either conditionals or loops. The loop statements while, do-while, and for allow us execute a statement(s) over and over. Like a conditional, a loop is controlled by a boolean expression that determines how many times the statement is executed. E.g., You may want to calculate the interest paid on a mortgage for each year of the loan term.

The while statement The form of the while statement is while (<boolean_expression>) <statement> If boolean_expression evaluates to true, then statement is executed. Then, the boolean_expression is evaluated again. If it evaluates to true, statement is executed again. This repetition continues until the boolean_expression evaluates to false. How is the while loop different from the if statement?

The if Flowchart boolean_expression false true statement (body of loop)

The while Flowchart boolean_expression false true statement (body of loop)

A while Example i n = 5 output Print n asterisks! i < n? 0 *! int i = 0;! while (i < n) {!! System.out.print( * );!!i++;! i < n? i < n? 1 2 **! ***! }! System.out.println();! i < n? 3 ****! i < n? 4 *****! i < n? 5 *****

The Loop Control Variable The variable i (known as the loop control variable) is used in three ways: it is initialized, tested, and updated.!!int i = 0;!!while (i < n) {!!! System.out.print( * );!!! i++;! // update!}!!system.out.println();! // initialize // test All three things must be coordinated in order for the loop to work correctly!

Off-by-1 Errors int i = 0;! while (i < n) {!!int i = 1;!!!while (i < n) {! System.out.print( * );!!!i++;!!system.out.print ( * );! }!!!i++;! System.out.println();! For n = 5 the output is ***** (5 asterisks)!}!!system.out.println();! Output?

Off-by-1 Errors int i = 0;! while (i < n) {!!int i = 0;!!!while (i <= n) {! System.out.print( * );!!!i++;!!system.out.print ( * );! }!!!i++;! System.out.println();! For n = 5 the output is ***** (5 asterisks)!}!!system.out.println();! Output?

Warning! int i = 0;! while (i < n) {! }!!! System.out.print( * );!!i--;!!what is the output if n = 5? System.out.println();!

Infinite Loops int i = 0;! while (i < n) {!!! System.out.print( * );!!i--;! }! System.out.println();! Do you know which company has this address? Apple Computer 1 Infinite Loop Cupertino, CA 95014

A while Example int i = 0;! while (i < n) {!! System.out.print( * );! }!!i++;! System.out.println();!!What is the output if n = 0?

Exercise Write a method with a while loop to prints 1 through n in square brackets. For example, if n = 6 print!![1] [2] [3] [4] [5] [6]!

Exercise: Cumulative Sum Write a method with a while loop that computes the sum of first n positive integers: sum = 1 + 2 + 3 + + n Examples: n = 5 sum = 15 n = 19 sum = 190

Exercise: Fencepost Loop Write a method with a while loop that prints 1 through n, separated by commas. E.g., for n = 9 print 1, 2, 3, 4, 5, 6, 7, 8, 9!

The do Statement The form of the do statement is do! <statement>!!while (<boolean_expression>); First, statement is executed. Then, the boolean_expression is evaluated. If it evaluates to true, statement is executed again. This repetition continues until the boolean_expression evaluates to false.

The do Flowchart true statement boolean_expression false

Example!int i = 0; // initialize!!do {!!! System.out.print( * );!!! i++; // update!!} while (i < n); // test!!system.out.println();! For n = 7 what is the output? How is it different from the while loop?

User Input Scanner keyboard = new Scanner(System.in);! System.out.print(!!! Please enter the month [1-12]: );! int month = keyboard.nextint();! What if the user enters a month outside the range?

User Input (cont d) Use a do-while loop to test whether a user has entered data of the correct form and, if not, ask repeatedly until the data entered is correct. Scanner keyboard = new Scanner(System.in);! int month;! Must be declared do {! outside the loop!system.out.print(!!! Please enter the month [1-12]: );!!month = keyboard.nextint();! } while ( month < 1 month > 12 );! Outside the scope of the loop

User Input Sometimes it is easier to think of what you want the input to be and negate. Scanner keyboard = new Scanner(System.in);! int month;! do {!!System.out.print(!!! Please enter the month [1-12]: );!!month = keyboard.nextint();! } while (!(month >= 1 && month <= 12) );! What is the loop control variable? Use de Morgan s law to prove the Boolean expressions are the same!

Sentinel Controlled Loops Suppose you want to find the maximum of the data entered from the keyboard. It is not known in advanced how many data values a user might want to enter. (And the user may not want to count them!) A sentinel is a special value that is used to detect a special condition, in this case that the user is done entering values. The sentinel, of course, must be distinct from any value the user may want to input.

Sentinel Example Scanner console = new Scanner(System.in);! System.out.print( Enter count (enter -1 to quit): );! int count = console.nextint();! int maxsofar = count;! while (count!= -1) {! if (count > maxsofar) maxsofar = count; System.out.print( Enter count (enter -1 to quit): );! count = console.nextint();! }! if (maxsofar > -1)!!System.out.println( The maximum is + maxsofar);! else!!system.out.println( No counts entered ); Consider making -1 a named constant