MORE ON LOOPS IN JAVA

Similar documents
SUBCLASSES IN JAVA - II

Programming via Java Subclasses

DELHI PUBLIC SCHOOL TAPI

Programming via Java User interaction

Programming via Java Defining classes

Introduction. C provides two styles of flow control:

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

LECTURE 5 Control Structures Part 2

CS112 Lecture: Repetition Statements

1 Getting used to Python

Object-Oriented Programming in Java

Loops. CSE 114, Computer Science 1 Stony Brook University

Scope of this lecture. Repetition For loops While loops

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

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

CS112 Lecture: Loops

Information Science 1

Information Science 1

int j = 0, sum = 0; for (j = 3; j <= 79; j++) { sum = sum + j; System.out.println(sum); //Show the progress as we iterate thru the loop.

CS201 Some Important Definitions

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

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

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

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

STUDENT LESSON A12 Iterations

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

Introduction to MiniSim A Simple von Neumann Machine

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

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

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

REPETITION CONTROL STRUCTURE LOGO

Here's how you declare a function that returns a pointer to a character:

Accelerating Information Technology Innovation

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

Slide 1 CS 170 Java Programming 1 The while Loop Duration: 00:00:60 Advance mode: Auto

CircuitPython 101: Working with Lists, Iterators and Generators

Repetition, Looping CS101

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

For Loop. Variations on Format & Specific Examples

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

Lecture 7: General Loops (Chapter 7)

Week - 04 Lecture - 01 Merge Sort. (Refer Slide Time: 00:02)

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

Control Flow Statements

Programming Lecture 4

Chapter 3 - Simple JavaScript - Programming Basics. Lesson 1 - JavaScript: What is it and what does it look like?

Principle of Complier Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Introduction to the Java Basics: Control Flow Statements

Programming Lecture 4

Assignment 1: grid. Due November 20, 11:59 PM Introduction

COMP-202 Unit 4: Programming with Iterations

Iterative Languages. Scoping

5.1. Chapter 5: The Increment and Decrement Operators. The Increment and Decrement Operators. Looping. ++ is the increment operator.

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

Compiler Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

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

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

(Refer Slide Time: 00:26)

Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5-1

Computer Programming I - Unit 5 Lecture page 1 of 14

Lecture Transcript While and Do While Statements in C++

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

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Control Structures. Control Structures Conditional Statements COMPUTER PROGRAMMING. Electrical-Electronics Engineering Dept.

Problem Solving With Loops

Loop structures and booleans

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Lecture 14. 'for' loops and Arrays

Prepared by: Shraddha Modi

Repetition Structures

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

Programming via Java Recursion

5. Control Statements

Repetition, Looping. While Loop

The for Loop. Lesson 11

ECE 122. Engineering Problem Solving with Java

Programming for Engineers Introduction to C

CS110D: PROGRAMMING LANGUAGE I

Chapter 2, Part I Introduction to C Programming

Objects and Graphics

CS 106 Introduction to Computer Science I

Flow Control. CSC215 Lecture

Learning to Program with Haiku

Computational Expression

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Basics of Computational Geometry

Data Structure Design II Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Hi everyone. I hope everyone had a good Fourth of July. Today we're going to be covering graph search. Now, whenever we bring up graph algorithms, we

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter Fourteen Bonus Lessons: Algorithms and Efficiency

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Transcription:

MORE ON LOOPS IN JAVA In this chapter we look at two new categories of statements the for loop and the break statement. Neither is very complex conceptually, but nonetheless they are convenient enough in practice that you wouldn't want to miss them. 9.1. The for loop You may have noticed by now that our programs often have loops incorporating some sort of counter variable, as in the following. int <var> = <initial>; while(<var> < <maximum>) { // do something once var++; This happens often enough that Java provides a shortcut for the situation in the form of a different type of loop called a for loop. The above example could instead be written as the following. for(int <var> = <initial>; <var> < <maximum>; <var>++) { // do something once Inside the parentheses of a for loop are three parts separated by semicolons. for(<initialization>; <condition>; <update>) { <statementstorepeat> When the Java compiler sees this, it automatically interprets it as if the user had written the following instead. <initialization>; while(<condition>) { <statementstorepeat> <update>;

In some sense, you may see the while loop as being easier to understand. But you should quickly be able to adapt to learning the for loop. Most programmers strongly prefer forloops to while loops whenever a program iterates over a sequence of numbers. This is because all the information about the numeric sequence is contained on one line, which makes the program shorter, easier to understand, and less liable to lead to bugs. These aren't really exactly equivalent. A significant difference is that if <initialization> incorporates a variable declaration, the declared variable's scope would be restricted to only within the for loop, but in the equivalent while loop formulation, the variable could be accessed following the while loop's end. (Another difference has to do with the continue statement, but this statement isn't often useful, and so we'll defer discussion of it to later.) As an example of this in practice, suppose we wanted to modify MovingBall of Figure 6.3 so that the program displays only 50 frames of the ball's movement before the program ends. The program of Figure 9.1 manages to accomplish this. Notice how it introduces a for loop to count how many frames have been displayed thus far. Figure 9.1: The MovingBall50 program. 5 public class MovingBall50 extends GraphicsProgram { 7 GOval ball = new GOval(25, 25, 50, 50); 8 ball.setfilled(true); 12 for(int frames = 0; frames < 50; frames++) { 13 pause(0); 1 ball.move(3, 2); 15 16 17 The for loop can be modified for virtually any numeric sequence. Suppose we want to count by fives up to 100.

for(int current = 5; current <= 100; current += 5) { println(current); Here, we've modified the <update> clause so that the current variable goes up by 5 with each iteration. Notice also that the <condition> clause uses less-than-or-equal rather than less-than. Suppose we want instead to count down from 10 to 1. In this case, we'll start our variable at 10, and we'll modify the <update> clause so that the variable is decremented with each iteration rather than incremented. for(int current = 10; current >= 1; current--) { println(current); The Break statement The break statement is another type of statement that sometimes turns out to be useful. It looks quite simple. break; When the computer reaches a break statement, it will immediate exit whichever loop it is in, proceeding to the statement following the loop's body. It's important to remember that an if statement is not a loop: If the break occurs in an if statement (as it almost always will be), the computer will look successive levels outside the if statement to find the loop from which to break. The program of Figure 9.2 illustrates an example where one might use a break statement. Here, after each movement of the ball, we test to see whether the ball has gone off the the window's edge; if the ball has gone off, the computer executes a break statement, which moves execution to after the while loop. In this program's case, the ball would start moving backwards indefinitely. Figure 9.2: The MovingBallBreak program. 5 public class MovingBallBreak extends GraphicsProgram {

7 GOval ball = new GOval(25, 25, 50, 50); 8 ball.setfilled(true); 12 while(true) { 13 pause(0); 1 ball.move(3, 2); 15 if(ball.getx() > getwidth() ball.gety() > getheight()) { 16 break; 17 18 19 while(true) { 20 pause(0); 21 ball.move(-3, -2); 22 23 2 (Incidentally, most programmers would argue that this program would be better written without a break statement. Instead, the if statement would go inside the while loop's condition. Still, this is a handy example with which to illustrate our point.) Sometimes you'll have one loop inside another. If the computer encounters a break statement, it applies only to the innermost loop. In the below example, the ball will go back and forth across the window 10 times. Each time the computer encounters the first break statement, it will break out of the first while loop rather than the for loop, since thewhile loop is the innermost loop containing that statement; and it would continue on to the second while loop. And each time the computer encounters the second breakstatement, the computer will decide whether to repeat the for loop for another lap. Figure 9.3: The MovingBallLaps program. 5 public class MovingBallLaps extends GraphicsProgram { 7 GOval ball = new GOval(25, 25, 50, 50);

8 ball.setfilled(true); 12 for(int laps = 0; laps < 10; laps++) { 13 while(true) { 1 pause(0); 15 ball.move(3, 2); 16 if(ball.getx() > getwidth() ball.gety() > getheight()) { 17 break; 18 19 20 while(true) { 21 pause(0); 22 ball.move(-3, -2); 23 if(ball.getx() < -50 ball.gety() < -50) { 2 break; 25 26 27 28 29