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

Similar documents
REPETITION CONTROL STRUCTURE LOGO

STUDENT LESSON A12 Iterations

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

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

Introduction. C provides two styles of flow control:

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

APCS Semester #1 Final Exam Practice Problems

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

Iteration statements - Loops

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition Structures

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

(Refer Slide Time: 00:26)

Controls Structure for Repetition

Week 2. Relational Operators. Block or compound statement. if/else. Branching & Looping. Gaddis: Chapters 4 & 5. CS 5301 Spring 2018.

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

Chapter Goals. Contents LOOPS

Introduction to Software Development (ISD) Week 3

/** * Utility class to support string reassembly from fragments. * Emily McIntyre * <pre> * * OVERLAPS ( * s1: string of

Looping. Arizona State University 1

Repetition, Looping CS101

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #43. Multidimensional Arrays

Repetition, Looping. While Loop

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

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

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

CS110D: PROGRAMMING LANGUAGE I

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

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

Loops / Repetition Statements

Repetition CSC 121 Fall 2014 Howard Rosenthal

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

Java Coding 3. Over & over again!

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

Example: Monte Carlo Simulation 1

Programming Lecture 4

CSE 114 Computer Science I

Top-Down Program Development

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

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

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

CS112 Lecture: Repetition Statements

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

Programming Lecture 4

Dept. of CSE, IIT KGP

Why Is Repetition Needed?

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

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

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

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

Chapter 7 User-Defined Methods. Chapter Objectives

Chapter 5: Loops and Files

3 The L oop Control Structure

Following is the general form of a typical decision making structure found in most of the programming languages:

Loops. CSE 114, Computer Science 1 Stony Brook University

Lecture Transcript While and Do While Statements in C++

Pace University. Fundamental Concepts of CS121 1

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

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

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

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

Iteration. CSE / ENGR 142 Programming I. Chapter 5. Motivating Loops. One More Type of Control Flow. What s Wrong with HW1?

Programming: Java. Chapter Objectives. Chapter Objectives (continued) Program Design Including Data Structures. Chapter 7: User-Defined Methods

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

(a) Assume that in a certain country, tax is payable at the following rates:

Loops. Repeat after me

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.

LOOPS. Repetition using the while statement

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Flow of Control: Loops. Chapter 4

Decision Making in C

Multiple-Subscripted Arrays

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Glossary. (Very) Simple Java Reference (draft, v0.2)

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

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.

Computer Programming I - Unit 5 Lecture page 1 of 14

Unit 3 Decision making, Looping and Arrays

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

Introduction to the Java Basics: Control Flow Statements

Programming Lecture 4

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

Repetition and Loop Statements Chapter 5

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

Scope of this lecture. Repetition For loops While loops

Chapter 4: Control structures. Repetition

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

204111: Computer and Programming

CS112 Lecture: Loops

For Loop. Variations on Format & Specific Examples

Lecture 5: Methods CS2301

Chapter 5: Control Structures

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

Transcription:

Java Loops & Methods The while loop Syntax: while ( condition is true ) { do these statements Just as it says, the statements execute while the condition is true. Once the condition becomes false, execution continues with the statements that appear after the loop. Example: int count = 1; while (count <= 10) { out.println(count); count = count + 1; This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10 This is an example of a counting loop. They are called this because the loop is just counting through the values of the loop control variable (LCV), which in this case is called count. It executes a definite number of times. while loops can also be used as indefinite loops when you can t pre-determine how many times the loop will execute. For example, let s take this problem. A colony of 800 puffins is increasing at the rate of 4% annually. When will their population first exceed 1200? Without doing the calculations, can we determine how many times this loop will run? No! We ll use a while loop to solve it, though:

import components.simplewriter.simplewriter; import components.simplewriter.simplewriter1l; / A colony of 800 Puffins is increasing at the rate of 4% annually. When will their population first exceed 1200? @author Chris Kiel public final class PuffinColony { / Private constructor so this utility class cannot be instantiated. private PuffinColony() { / Main method. @param args the command line arguments public static void main(string[] args) { final double GROWTH_RATE = 0.04; SimpleWriter out = new SimpleWriter1L(); int population, year; //Initializations population = 800; year = 0; //zero years from now; i.e., the present time while (population <= 1200) { //we do not want fractional Puffins! population = (int) (population (1 + GROWTH_RATE)); year++; //Output results out.println("the population first goes over 1200 after " + year + " years."); out.println("after that time, the population is " + population + "."); / Close output stream out.close();

/ Output The population first goes over 1200 after 11 years. After that time, the population is 1225. Infinite Loops A loop is called an infinite loop if it never ends. Obviously, we don t want to have these! Examples: int count = 1; while (count <= 10) { out.println(count); count = count 1; Why is this an infinite loop? count starts at 1, then goes to 0, -1, -2, etc., never getting greater than 10, which is needed to make the condition false! So this loop never ends. int count = 1; while (count!= 10) { out.println(count); count = count + 2; Why is this one an infinite loop? count starts at 1, then goes to 3, 5, 7, 9, 11, etc., never equalling 10, so the loop is infinite. int count = 1; while (count <= 10); { out.println(count); count = count + 1; Did you see what makes this an infinite loop? Look after the condition. See the semicolon? Remember that the ; is a statement terminator. What the compiler determines is this: int count = 1; while (count!= 10) { //do nothing Since nothing is taking place inside the loop which is an empty statement followed by a ; - the condition never becomes false and the loop is infinite.

Important while loop rules: 1. The condition must eventually become false. 2. Never put a semicolon after the condition unless you want an infinite loop. So what if you accidentally write an infinite loop in your program? Everyone does at some point! Often your only clue is lines of output streaming by on the Console or you see nothing at all. All you have to do is either press <Ctrl-C> or click the red square in the Console bar to stop the program. The while loop is the generic loop; every loop can be written as a while loop. The for loop A for loop is a counting loop. for ( initializer ; loop entry condition ; updater ) { do these statements The initializer gives an initial value to the loop control variable (LCV) The loop entry condition must be true for the loop to execute The updater helps the LCV to reach a state when the condition will eventually become false Examples: for (int count = 1; count <= 100; count++){ out.println("hello"); Semantics: count initialized to one 1. condition checked; is true 2. println executed 3. count incremented 4. repeat steps 1-3 until condition is false (count > 100), then continue to next statement after loop Note: if you have a one-statement loop, you don t need the curly braces. However, while you are learning how to write these structures, I recommend you use them! The increment does not have to be 1: for (int count = 1; count <= 100; count+=2) { out.println("hello");

Another well-known example : int count; for (count = 100; count >= 0; count--) { out.println(count + " bottles of beer on the wall"); What is the value of count after the end of this loop? For loops can be skipped if initial condition is false: for (int count = 10; count < 10; count--) { out.print(count); out.println(); Notice the use of the increment and decrement shortcut operators in these loops. They are not required, but most programmers use them. Loop Variable Scope If count is declared within the for loop, it cannot be used after the for statement: for (int count = 1; count <= 100; count++) { out.println("hello"); out.println(" count = " + count); // Syntax error, count undeclared If count is declared before the for statement, it can be used after the for loop: int count; // Declare the loop variable here for (count = 1; count <= 100; count++) { out.println("hello"); out.println("count = " + count); // So it can be used here Nested Loops You can nest one structure inside of another. We have seen that you can nest one if statement inside of another; not surprisingly, we can also nest one loop inside of another. Think of them like gears; the outer one goes slowly, the inner one goes quickly. In other words, for every execution of the outer loop, there are multiple executions of the inner loop.

Suppose you wanted to print the following table: 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 You could use a nested for loop. The outer loop prints the four rows and in each row, the inner loop prints the nine columns. // For each of 4 rows for (int row = 1; row <= 4; row++) { for (int col = 1; col <= 9; col++) { out.print(col row + "\t"); //Print one row out.println(); // Start a new row Make a table to show the relationship between the row and column variables needed to print the following triangular pattern: ##### #### ### ## # You could use the following nested for loop. for (int row = 1; row <= 5; row++) { for (int col = 1; col <= 6 - row; col++) { out.print('#'); out.println(); Loop Review Three loops: for, while, do while Which do you use? Depends on what you need to do: Do you need to produce values like 1..10, 50..100, etc? counting loop for loop Is it not determinable in advance how many times the loop will run? indefinite loop while loop

How to decide what loop to use If you know ahead of time exactly how many times loop should be executed, use a for loop. You can know this if you know the constant (e.g., 5) or there is a variable containing the number of times to execute the loop (e.g., numtimes). For loops are also very good for numerical calculations and counting loops, and are optimized structures in the compiler. If the loop might need to be skipped, use a while loop Remember that all loops can be written as while loops, but the reverse is not true. Common loop errors empty loops for (int count=1; count<=10; count++); //Notice the ; while(count<=10); Neither of these loops has any statements inside of it, so nothing happens in them! loop boundary problems //how many times do these loops execute? for (int count = 1; count <= 10; count++) for (int count = 1; count < 10; count++) for (int count = 0; count < 10; count++) for (int count = 10; count > 10; count--)

Common problem: Finding max or min Finding the max/min requires certain things: declare variables for max/min initialize max/min before the loop initialize max/min in one of two ways: by setting them to the first data value by setting them to the predefined constant Integer.MIN_VALUE or Integer.MAX_VALUE inside the loop, check each data value, changing max/min as required after the loop is the time to display the values for max/min We will use a sentinel loop, which stops when it checks for a sentinel value (some value that does not belong to data set) Sentinel loop format: get data value while (value!= sentinel){ //process value... get data value import components.simplereader.simplereader; import components.simplereader.simplereader1l; import components.simplewriter.simplewriter; import components.simplewriter.simplewriter1l; / Finds max & min values from ints in a file. @author Chris Kiel public final class MinMax { / Private constructor so this utility class cannot be instantiated. private MinMax() {

/ Prompts for and returns int entered by user. @param in the input stream @param out the output stream @return int input from user. private static int getinput(simplereader in, SimpleWriter out) { out.print("enter a number, -1 to quit: "); return in.nextinteger(); / Calculates and returns average. @param sum sum of ints @param count count of ints @return average, zero if empty private static double calcavg(int sum, int count) { double avg = 0; if (count > 0) { avg = (double) sum / count; return avg;

/ Prints results of calculations. @param out the output stream @param sum sum of ints @param count count of ints @param max max of ints @param min min of ints private static void printresults(simplewriter out, int sum, int count, int max, int min) { out.println("\nthere were " + count + " numbers."); out.println("the maximum of the numbers was " + max); out.println("the minimum of the numbers was " + min); out.println("the sum of the numbers was " + sum); out.println("the average of the numbers was " + calcavg(sum, count)); / Main method. @param args the command line arguments public static void main(string[] args) { SimpleReader in = new SimpleReader1L(); SimpleWriter out = new SimpleWriter1L(); int number, sum, count; int max, min; //initializations sum = 0; count = 0; max = Integer.MIN_VALUE; //initialize to smallest int possible min = Integer.MAX_VALUE; //initialize to largest int possible

/ Use sentinel loop to get data, determine max, min, sum & count //Priming read number = getinput(in, out); while (number!= -1) { //check for max, min if (number > max) { //Why use separate ifs, not max = number; // if..else? if (number < min) { min = number; //accumulate sum, count sum = sum + number; count++; //Input data number = getinput(in, out); printresults(out, sum, count, max, min); / Close input and output streams in.close(); out.close(); //Output //Enter a number, -1 to quit: 2 //Enter a number, -1 to quit: 8 //Enter a number, -1 to quit: 32 //Enter a number, -1 to quit: 4 //Enter a number, -1 to quit: 5 //Enter a number, -1 to quit: 17 //Enter a number, -1 to quit: -1 // //There were 6 numbers. //The maximum of the numbers was 32 //The minimum of the numbers was 2 //The sum of the numbers was 68 //The average of the numbers was 11.333333333333334

Single-entry, Single-exit It is important for our control structures to have a single entry and a single exit. For example, instead of writing a loop with one return statement inside the loop and another after the loop, write the structure with one return statement only this applies to methods as well; good design means single entry, single exit For example, take the calcavg(sum, count) method above. We could have said private static double calcavg(int sum, int count) { if (count > 0) { return (double) sum / count; else { return 0; but instead of this, we used a local double variable, set its value in the method, and had only one return statement: private static double calcavg(int sum, int count) { double avg = 0; if (count > 0) { avg = (double) sum / count; return avg; Notice the single return statement; this is a better design If we were to have a logical error, it would be much easier to trace this version than the previous one. I am requiring you to do it this way!! (You ll thank me later!) This leads to some basic rules for value-returning methods.

Rules for Value-Returning Methods In a value-returning method: Declare a local variable of the same type as the method. Use this local variable for your calculations inside the method, ultimately assigning it a value. Return this local variable at the end of the method. Do not print inside these methods; rather, call them from a printing statement. Calling Value-Returning Methods Three ways to call value-returning methods: 1. On the right-hand side of an assignment statement: double average = calcavg(sum, count); 2. In an output statement: out.println("the average is " + calcavg(sum, count)); 3. In a condition: if (isprime(n))