Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Similar documents
Oct Decision Structures cont d

What two elements are usually present for calculating a total of a series of numbers?

Repetition, Looping. While Loop

Computer Programming I - Unit 5 Lecture page 1 of 14

What methods does the String class provide for ignoring case sensitive situations?

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Chapter 4: Loops and Files

Chapter 4: Loops and Files

Iteration: Intro. Two types of loops: 1. Pretest Condition precedes body Iterates 0+ times. 2. Posttest Condition follows body Iterates 1+ times

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

Problem Solving With Loops

Repetition, Looping CS101

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Loops. CSE 114, Computer Science 1 Stony Brook University

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Lesson 7 Part 2 Flags

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Over and Over Again GEEN163

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

4. If the following Java statements are executed, what will be displayed?

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

STUDENT LESSON A12 Iterations

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

The action of the program depends on the input We can create this program using an if statement

Loops. GEEN163 Introduction to Computer Programming

Arithmetic Compound Assignment Operators

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

++x vs. x++ We will use these notations very often.

AP Programming - Chapter 6 Lecture

Flow of Control: Loops. Chapter 4

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Controls Structure for Repetition

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

COMP 202 Java in one week

Date: Dr. Essam Halim

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Full file at

Lec 3. Compilers, Debugging, Hello World, and Variables

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

3chapter C ONTROL S TATEMENTS. Objectives

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Gaddis: Starting Out with Java: From Control Structures through Objects, 6/e

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Starting Out with Java: From Control Structures through Data Structures 3e (Gaddis and Muganda) Chapter 2 Java Fundamentals

St. Edmund Preparatory High School Brooklyn, NY

Lesson 6A Loops. By John B. Owen All rights reserved 2011, revised 2014

Java Basic Programming Constructs

switch-case Statements

Chapter 3 Selection Statements

Iteration statements - Loops

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Chapter 3. Selections

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Programming with Java

Task #1 The if Statement, Comparing Strings, and Flags

Java Coding 3. Over & over again!

A+ Computer Science -

Conditional Programming

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Warm-Up: COMP Programming with Iterations 1

Object-Oriented Programming in Java

Warmup : Name that tune!

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Repetition. Chapter 6

Repetition. Chapter 6

Top-Down Program Development

Computer Science is...

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Introduction to Java & Fundamental Data Types

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Example. Write a program which generates 2 random integers and asks the user to answer the math expression.

Basic Computation. Chapter 2

Conditional Execution

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

Section 2.2 Your First Program in Java: Printing a Line of Text

COMP 202. Java in one week

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Transcription:

Dec. 9 Loops Please answer the following questions. Do not re-code the enclosed codes if you have already completed them. What is a loop? What are the three loops in Java? What do control structures do? What are the two parts of a while loop? What is the loop header? What is the statement that is repeated known as? Why is it considered to be a conditionally executed statement? What is an iteration? What does a pretest loop do? What happens if the boolean expression is false to begin with? What kind of expression will stop a loop? If it does not stop what is it called? Give an example of an infinite loop. What is the semi colon assumed to be and what does it do? What is input validation? What is a priming read and what does it do? What is the do-while loop and when is its boolean expression tested? What are the two categories of loops? What is a conditional loop?

What is a count controlled loop? The while Loop CONCEPT: A loop is part of a program that repeats. In Chapter 3, you were introduced to the concept of control structures, which direct the flow of a program. A loop is a control structure that causes a statement or group of statements to repeat. Java has three looping control structures: the while loop, the dowhile loop, and the for loop. The difference among each of these is how they control the repetition, In this section we will focus on the while loop. The while loop has two important parts: (1) a boolean expression that is tested for a true or false value, and (2) a statement or block of statements that is repeated as long as the expression is true. Figure 4-1 shows the logic of a while loop. In the general format, BooleanExpression is any valid boolean expression, and Statement is any valid Java statement. The first line shown in the format is sometimes called the loop header. It consists of the key word while followed by the BooleanExpression enclosed in parentheses. Here's how the loop works: the BooleanExpression is tested, and if it is true, the Statement is executed. Then, the BooleanExpression is tested again. If it is true, the Statement is executed. This cycle repeats until the BooleanExpression is false. The statement that is repeated is known as the body of the loop. It is also considered a conditionally executed statement, because it is only executed under the condition that the BooleanExpression is true. Notice there is no semicolon at the end of the loop header. Like the if statement, the while loop is not complete without the conditionally executed statement that follows it. If you wish the while loop to repeat a block of statements, the format is as follows: while (BooleanExpression) Statement; Statement; // Place as many statements here // as necessary.

The while loop works like an if statement that executes over and over. As long as the expression in the parentheses is true, the conditionally executed statement or block will repeat. The program in Code Listing 4-3 uses the while loop to print "Hello" fi'.c times. (WhileLoop. java) /** * This program demonstrates the while loop. * @author monzootles * */ public class WhileLoop public static void main(string[] args) int number = 1; while (number <= 5) System.out.println("Hello"); number++; System.out.println("That's all!"); Program Output: Hello Hello Hello Hello Hello That's all! Let's take a closer look at this program. An integer variable, number, is declared and initialized with the value 1. The while loop begins with the following statement: while (number <= 5)

This statement tests the variable number to determine whether it is less than or equal to 5. If it is, then the statements in the body of the loop are executed as follows: System.out.println("Hello"); number++; The first statement in the body of the loop prints the word "Hello". The second statement uses the increment operator to add one to number. This is the last statement in the body of the loop, so after it executes, the loop starts over. It tests the boolean expression again, and if it is true, the statements in the body of the loop are executed. This cycle repeats until the boolean expression number <= 5 is false. Each repetition of a loop is known as an iteration. This loop will perform five iterations because the variable number is initialized with the value 1, and it is incremented each time the body of the loop is executed. When the expression number <= 5 is tested and found to be false, the loop will terminate and the program will resume execution at the statement that immediately follows the loop. The while Loop Is a Pretest Loop The while loop is known as a pretest loop, which means it tests its expression before each iteration. Notice the variable declaration of number in Code Listing 4-3: int number = 1; The number variable is initialized with the value 1. If number had been initialized with a value that is greater than 5, as shown in the following program segment, the loop would never execute: int number = 6; while (number <= 5) System.out.println("Hello"); number++; An important characteristic of the while loop is that the loop will never iterate if the boolean expression is false to start with. If you want to be sure that a while loop executes the first time, you must initialize the relevant data in such a way that the boolean expression starts out as true. Infinite Loops In all but rare cases, loops must contain a way to terminate within themselves. This means that something inside the loop must eventually make the boolean expression false. The loop in Code Listing 4-3 stops when the expression number <= 5 is false.

If a loop does not have a way of stopping, it is called an infinite loop. An infinite loop continues to repeat until the program is interrupted. Here is an example of an infinite loop: int number = 1; while (number <= 5) System.out.println("Hello"); This is an infinite loop because it does not contain a statement that changes the value of the number variable. Each time the boolean expression is tested, number will contain the value 1. It's also possible to create an infinite loop by accidentally placing a semicolon after the first line of the while loop. Here is an example: int number = 1; while (number <= 5); // This semicolon is an ERROR! System.out.println("Hello"); number++; The semicolon at the end of the first line is assumed to be a null statement and disconnects the while statement from the block that comes after it. To the compiler, this loop looks like the following: while (number <= 5); This while loop will forever execute the null statement, which does nothing. The program will appear to have "gone into space" because there is nothing to display screen output or show activity. Don't Forget the Braces with a Block of Statements If you are using a block of statements, don't forget to enclose all of the statements in a set of braces. If the braces are accidentally left out, the while statement conditionally executes only the very next statement. For example, look at the following code: int number = 1; // This loop is missing its braces! while (number <= 5) System.out.println("Hello")i number++;

In this code the number++ statement is not in the body of the loop. Because the braces are missing, the while statement only executes the statement that immediately follows it. This loop will execute infinitely because there is no code in its body that changes the number variable. Programming Style and the while Loop It's possible to create loops that look like the following: while (number <= 5) System.out.println("Hello"); number++; Avoid this style of programming. The programming style you should use with the while loop is similar to that of the if statement as follows: If there is only one statement repeated by the loop, it should appear on the line after the while statement and be indented one additional level. The statement can optionally appear inside a set of braces. If the loop repeats a block, each line inside the braces should be indented. This programming style should visually set the body of the loop apart from the surrounding code. In general, you'll find a similar style being used with the other types of Ioops presented in this chapter. Checkpoint 4.2 How many times will "Hello world" be printed in the following program segment? int count = 10; while (count < 1) System.out.println("Hello World"); count++; 4.3 How many times will" I love Java programming!" be printed in the following program segment? int count = 0; while (count < 10)

system.out.println("i love Java programming!); Using the while Loop for Input Validation CONCEPT: The while loop can be used to create input routines that repeat until acceptable data is entered. Perhaps the most famous saying of the computer industry is "garbage in, garbage out. The integrity of a program's output is only as good as its input, so you should try to inssure garbage does not go into your programs. Input validation is the process of inspecting data given to a program by the user and determining if it is valid. A good program should give clear instructions about the kind of input that is acceptable, and not assume the user has followed those instructions. The while loop is especially useful for validating input. If an invalid value is entered, a loop can require that the user re-enter it as many times as necessary. For example, the foliowing loop asks for a number in the range of 1 through 100: input = JOptionpane.showlnputDialog("Enter a number" + "in the range of 1 through 100."); number = Integer.parselnt(input); // Validate the input. while (number < 1 I I number> 100) input = JOptionpane.showlnputDialog("InValid input. " + "Enter a number in the range of " + "1 through 100."); number = Integer.parselnt(input); This code first allows the user to enter a number. This takes place just before the loop input is valid, the loop will not execute. If the input is invalid, however, the loop will continue to an error message and require the user to enter another number. The loop will continue to execute until the user enters a valid number. The general logic of performing input validation is shown in Figure 4-4. The read operation that takes place just before the loop is called a priming read. It provides the first value for the loop to test. Subsequent values are obtained by the loop. The program in Code Listing 4-5 calculates the number of soccer teams a youth league may create, based on a given number of players and a maximum number of players per team. The program uses while loops (in lines 28 through 36 and lines 44 through 49) to validate the user's input. Figure 4-5 shows an example of interaction with the program.

(SoccerTeams.java) import javax.swing.joptionpane; /** * This program calculates the number of soccer teams * that a youth league may create from the number of available * players. Input validation is demonstrated with while loops. * * @author monzootles * */ public class SoccerTeams public static void main(string [] args) final int MIN_PLAYERS = 9; // Minimum players per team. final int MAX_PLAYERS = 15; // Maximum players per team. int players; // Number of available players. int teamsize; // Number of players per team. int teams; // Number of teams. int leftover; // Number of leftover players. String input; // To hold the user input. // Get the number of players per team. input = JOptionPane.showInputDialog("Enter the number of " + "players per team."); teamsize = Integer.parseInt(input); // Validate the number entered. while (teamsize < MIN_PLAYERS teamsize > MAX_PLAYERS) input = JOptionPane.showInputDialog("The number must " + "be at least " + MIN_PLAYERS + " and no more than " + MAX_PLAYERS + ".\n Enter " + "the number of players."); teamsize = Integer.parseInt(input); // Get the number of available players. input = JOptionPane.showInputDialog("Enter the available " + "number of players.");

players = Integer.parseInt(input); // Validate the number entered. while (players < 0) input = JOptionPane.showInputDialog("Enter 0 or " + "greater."); players = Integer.parseInt(input); // Calculate the number of teams. teams = players / teamsize; // Calculate the number of left over players. leftover = players % teamsize; over."); // Display the results. input = JOptionPane.showInputDialog(null, "There wil be " + teams + " teams with " + leftover + " players left System.exit(0); The do-while Loop CONCEPT: The do-while loop is a posttest loop, which means its boolean expression is tested after each iteration. The do-while loop looks something like an inverted while loop. Here is the do-while loop's format when the body of the loop contains only a single statement: do Statement; while (BooleanExpression); Here is the format of the do-while loop when the body of the loop contains multiple statements: do Statement; Statement;

// Place as many statements here as necessary. while (BooleanExpression); NOTE: The do-while loop must be terminated with a semicolon. The do-while loop is a posttest loop. This means it does not test its boolean expression until it has completed an iteration. As a result, the do-while loop always performs at least one iteration, even if the boolean expression is false to begin with. This differs from the behavior of a while loop, which you will recall is a pretest loop. For example, in the following while loop the println statement will not execute at all: int x = 1; while (x < 0) system.out.println(x); But the println statement in the following do-while loop will execute once because the do-while loop does not evaluate the expression x < a until the end of the iteration. int x = 1; do System.out.println(x); while (x < 0); You should use the do-while loop when you want to make sure the loop executes at least once. For example, the program in Code Listing 4-6 averages a series of three test scores for a student. After the average is displayed, it asks the user if he or she wants to average another set of test scores. The program repeats as long as the user enters y for yes. import java.util.scanner; // Needed for the Scanner class. /** * This program demonstrates a user controlled loop * @author monzootles * */ public class TestAverage1 public static void main(string [] args) int score1, score2, score3; // Three test scores double average; // Average test score char repeat; // To hold y or n

String input; // To hold input System.out.println("This program calculates the " + "average of three test scores."); // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get as many sets of test scores as the user wants. do // Get the first test score in this set. System.out.print("Enter score #1: "); score1 = keyboard.nextint(); // Get the second test score in this set. System.out.print("Enter score #2: "); score2 = keyboard.nextint(); // Get the third test score in this set. System.out.print("Enter score #3: "); score3 = keyboard.nextint(); // Consume the remaining newline keyboard.nextline(); // Calculate and print the average test score average = (score1 + score2 + score3) / 3.0; System.out.println("The average is " + average); System.out.println(); // Prints a blank line // Does the user want to average another set? System.out.println("Would you like to average " + "another set of test scores?"); System.out.println("Enter Y for yes or N for no: "); input = keyboard.nextline(); // Read a line. repeat = input.charat(0); // Get the first char. while (repeat == 'Y' repeat == 'y');

Program Output: This program calculates the average of three test scores. Enter score #1: 89 Enter score #2: 90 Enter score #3: 97 The average is 92.0 Would you like to average another set of test scores? Enter Y for yes or N for no: y Enter score #1: 78 Enter score #2: 65 Enter score #3: 88 The average is 77.0 Would you like to average another set of test scores? Enter Y for yes or N for no: n When this program was written, the programmer had no way of knowing the number of times the loop would iterate. This is because the loop asks the user if he or she wants to repeat the process. This type of loop is known as a user controlled loop, because it allows the user to decide the number of iterations.