Warm-Up: COMP Programming with Iterations 1

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

COMP-202 Unit 4: Programming with Iterations

Warmup : Name that tune!

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

Warm-up: What type of variable should we create to store the following information:

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

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

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Conditional Programming

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

Repetition, Looping. While Loop

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

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

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

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Conditionals and Loops

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

Control Structures in Java if-else and switch

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

Loops. CSE 114, Computer Science 1 Stony Brook University

Building Java Programs Chapter 2

Chapter 3. Selections

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

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

Last Class. While loops Infinite loops Loop counters Iterations

Top-Down Program Development

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

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

COMP-202 Unit 9: Exceptions

STUDENT LESSON A12 Iterations

Oct Decision Structures cont d

COMP-202 Unit 9: Exceptions

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

COMP 202 Java in one week

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

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

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

Java Coding 3. Over & over again!

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

CS 106 Introduction to Computer Science I

CS1004: Intro to CS in Java, Spring 2005

Repetition CSC 121 Fall 2014 Howard Rosenthal

COMP 202 Java in one week

Example: Computing prime numbers

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Algorithms and Conditionals

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

! 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

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Programming with Java

St. Edmund Preparatory High School Brooklyn, NY

What did we talk about last time? Examples switch statements

Computer Programming I - Unit 5 Lecture page 1 of 14

Object-Oriented Programming

COMP 202. Java in one week

Condi(onals and Loops

Garbage Collection (1)

Chapter 3: Operators, Expressions and Type Conversion

Program Fundamentals

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

Chapter 4 Lab. Loops and Files. Objectives. Introduction

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

AP Computer Science Unit 1. Programs

Control Structures in Java if-else and switch

Full file at

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

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

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Repetition, Looping CS101

Building Java Programs

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings

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

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Java I/O and Control Structures

Iteration statements - Loops

Building Java Programs

Chapter 4: Conditionals and Loops

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Computational Expression

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

Building Java Programs

Topics. Chapter 5. Equality Operators

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Over and Over Again GEEN163

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Computer Science is...

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Topic 4 Expressions and variables

Chapter Goals. Contents LOOPS

Transcription:

Warm-Up: Suppose I have a method with header: public static boolean foo(boolean a,int b) { if (a) return true; return b > 0; Which of the following are valid ways to call the method and what is the result? int x = foo(true, 3 + 4); System.out.println(foo(!true, -10)); System.out.println(foo(true && false, 1.0 / 2)); System.out.println(foo(foo(false,0), (int)1.0 / 2)); boolean a = foo(foo(false true, 3), -10); COMP-202 - Programming with Iterations 1

Part 5: Boolean Expressions -- (a.k.a. the things you put in if statements and other things as conditions)

Boolean Expressions The year is 2012 -----> true There are 15 months in a year ----> false September is the 9 th month AND it is 2 months before February ---> false The Rangers were stupid to get rid of Jaromir Jagr -----> true Pirates helped stop global warming---> true??? Comp-202 is awesome ---->??????? COMP-202 - Programming Basics 3

Boolean Expressions Instead of evaluating to a numeric value, boolean expressions evaluate to either true or false mynumber > 0 // can be either true or false You can assign the result of a boolean expression to a variable of type boolean: boolean positive; positive = (mynumber > 0); COMP-202 - Programming Basics 4

Expressions in general An expression is one of the following A literal value (e.g. 10, 10.0, 10.0f, 'c', foo ) A variable (e.g. x, foo, whatever) A call to a method that returns a value (e.g. Math.pow(3,4)) A combination of other expressions using operators such as +,-,/, etc COMP-202 - Conditional Programming 5

Boolean Expressions in Java A boolean expression is a specific sort of these expressions. There are several ways to form boolean expressions. A boolean literal value ( true or false) A variable of type boolean (e.g. x, foo, whatever) A call to a method that returns a boolean value A combination of other expressions using operators: Comparison operators (take numbers and return boolean) Boolean operators (take booleans and return boolean) COMP-202 - Conditional Programming 6

Comparison Operators (1) The result of a comparison is always true or false Used to compare numeric or character values == : equal to!= : not equal to < : less than > : greater than <= : less than or equal to >= : greater than or equal to COMP-202 - Conditional Programming 7

Comparison Operators (2) int x = 5; x < 6 ----> true x <= 5; ----> true x > 5 ---> false x >= 3 ---> true x == 5 ----> true x!= 5 ---> false COMP-202 - Conditional Programming 8

Comparison Operators (3) Equality (==) and inequality (!=) operators apply to values that have any type The other comparison operators (<, <=, >, >=) only apply to values which have a numeric type (byte, short, int, long, float, double) or that have type char If the operands of a comparison operator have different types, the operand whose type has lower precision gets promoted to the other operand's type COMP-202 - Conditional Programming 9

Comparing Strings When you want to compare two Strings to each other, you will not use = = Instead you will call a method on each String. String one = a String ; String two = a different String ; boolean areequal = one.equals(two); We will see when we talk about references when you should use.equals() and when you should use = =. For primitive types like int, always use ==, for String it's almost always best to use.equals() COMP-202 - Conditional Programming 10

Comparing char In Java, each character (like '?' or 'm') is associated with a number. The following expression evaluates to true because the number assigned to the character '+' by the Unicode character set is lower than the number assigned to the character 'J' by the same character set: boolean lessthan = '+' < 'J'; Do not hesitate to use this property of characters in your programs. COMP-202 - Conditional Programming 11

Unicode Chart symbols Associated numbers Notice that A-Z are 26 codes In a row, as are a-z, and 0-9 are 10 codes in a row. This means to check a char Is uppercase you could check If the code is between 'A' And 'Z' COMP-202 - Conditional Programming 12

Character Comparisons The unicode number system is well designed. The 26 lowercase letters are all in a row. The 26 uppercase letters are also in a row. Note that there is a gap between the two. This means that 'a' < 'c' ----> true. COMP-202 - Conditional Programming 13

Floating Point Comparisons You should rarely use the equality operator (==) when comparing two floating point values (float or double) In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal This is often necessary due to rounding issues. COMP-202 - Conditional Programming 14

Floating Point Comparisons: Example // Assuming f1 >= f2 difference = f1 - f2; boolean essentiallyequal = difference < 0.00001; COMP-202 - Conditional Programming 15

Creating boolean expressions from other boolean expressions Boolean expressions can also use the following logical operators:! Logical NOT Logical OR && Logical AND All three operators take operands of type boolean and produce results of type boolean That is, the input to the operator is boolean(s) and the output is a boolean. COMP-202 - Conditional Programming 16

! operator The! operator refers to not It takes as input one boolean expression and flips the result. So if the boolean expression was true before, then it is false now. COMP-202 - Conditional Programming 17

! operator examples! (2 < 3) ------> false (since 2 < 3)! (3 < 2) -----> true! true --------> false! false ------> true! (! (3 > 2)) ---> true!(september comes after August) ---> false!(earth is the 6 th planet from the sun) ---> true!(the Rangers are stupid for getting rid of Jagr) ---> false COMP-202 - Conditional Programming 18

&& operator The && operator refers to and It takes as input two boolean expressions. The result of this operator is true if both operands are true and false if at least one of the operands is false. COMP-202 - Conditional Programming 19

&& operator 1 < 2 && 2 < 3 -----> true 1 < 1 && 2 < 3 -----> false! (1 < 1) && 2 < 3 -----> true (Television starts with a T) && (Java can also be coffee) --> true COMP-202 - Conditional Programming 20

operator The operator refers to or It takes as input two boolean expressions. The result of this operator is true if at least one of the operands is true and false if at both of the operands are false. Note that the or is NOT exclusive. This means if both operands are true the result will be true. COMP-202 - Conditional Programming 21

operator examples 1 < 1 2 < 3 ------> true! (3 < 4 100 > 1000 ) ---> false (Vegetables are healthy) (Fruit is healthy) ---> true COMP-202 - Conditional Programming 22

How The Java Compiler Evaluates && and If left operand of a && expression evaluates to false, the remaining operands are not evaluated In p1 && p2, if p1 is false, p2 is never looked at. If left operand of a expression evaluates to true, the remaining operands are not evaluated In p1 p2, if p1 is true, p2 is never looked at. This is called short-circuit evaluation. COMP-202 - Conditional Programming 23

Aside: How The Java Compiler Evaluates && and This is useful in the following case. Suppose you have an int variable x and you aren't sure if x is equal to zero or not. if ( x!= 0 && 1 / x < 5 ) COMP-202 - Conditional Programming 24

A bit on clean code using boolean expessions boolean tall = height > 6.0; if(tall == true) x = 5; The above is not needed. Remember that the if statement always checks if the condition is true. So if (tall) tests is tall true if (tall == true) tests is it true that tall is equal to true, which is the same thing. COMP-202 - Conditional Programming 25

Careful... boolean tall = height > 6.0; if(tall = true) x = 5; This sets tall to true, so x = 5 always executes, regardless of the value of height. This is a logical error: compiler will not detect it! COMP-202 - Conditional Programming 26

Exercise: Complete the main() method of the MinOfThree class by adding code which determines which of the three numbers entered by the user is the smallest number, and displays that number COMP-202 - Conditional Programming 27

MinOfThree.java import java.util.scanner; public class MinOfThree { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); int num1, num2, num3, min; System.out.print("Enter a number: "); num1 = keyboard.nextint(); System.out.print("Enter another number: "); num2 = keyboard.nextint(); System.out.print("Enter a third number: "); num3 = keyboard.nextint(); // Add your code here COMP-202 - Conditional Programming 28

Advanced Conditional Statements (not examinable) 1) The switch statement 2) The conditional operator

The Conditional Operator condition? expression1 : expression2 If condition evaluates to true, then expression1 is evaluated; if it evaluates to false, then expression2 is evaluated COMP-202 - Conditional Programming 30

Conditional Operator Examples larger = (num1 > num2)? num1 : num2; If num1 is greater that num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger COMP-202 - Conditional Programming 31

Conditional operator vs. if-else The conditional operator is like an if-else statement, except that instead of executing one of two possible branches, it evaluates to one of two possible values. larger = (num1 > num2)? num1 : num2;...is the same as: if (num1 > num2) larger = num1; else larger = num2; COMP-202 - Conditional Programming 32

Conditional Operator Examples System.out.println ("Your change is " + count + " dime" + ((count == 1)? "" : "s")); If count evaluates to 1, then "dime" is printed If count evaluates to any value other than 1, then an "s" is added at the end of "dime" COMP-202 - Conditional Programming 33

Usefulness: Variable scope if (x < 0) { int absolutevalue = -x; else { int absolutevalue = x; //We can't use variable absolutevalue //here because we finished the { // it was declared in. COMP-202 - Conditional Programming 34

Usefulness: Variable scope int absolutevalue; if (x < 0) { absolutevalue = -x; else { absolutevalue = x; //Now we can use absolutevalue but //it's less clean To make sure //it got set, we need to remember both if/else COMP-202 - Conditional Programming 35

Solution 1: Use/write a method int absolutevalue = Math.abs(x); //Great when the method already exists! COMP-202 - Conditional Programming 36

Solution 2: Use conditional operator int absolutevalue = x < 0? -x : x; Another example: public static double myabsolutevalue(double x) { return x < 0? -x : x; COMP-202 - Conditional Programming 37

COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Repetition Statements Repetition statements allow us to execute a block of code or (set of) statement(s) multiple times; -These statements are normally called loops COMP-202 - Programming with Iterations 39

Repetition Statements in Java -Java has two main kinds of repetition statements: the while loop and the for loop - While and for loops are equivalent However, in certain circumstances, choosing one of these statements over the other results in a program that is easier to understand. COMP-202 - Programming with Iterations 40

Part 1: While loops

Recall : If statement if (condition) { //some code here... //code here happens regardless COMP-202 - Programming with Iterations 42

Recall : If statement if (condition) { //some code here... //code here happens regardless An if statement defines a block of code. COMP-202 - Programming with Iterations 43

Recall : If statement if (condition) { //some code here... //code here happens regardless We test a condition which can be any boolean expression. COMP-202 - Programming with Iterations 44

Recall : If statement if (condition) { //some code here... //code here happens regardless If the condition evaluates to true then we execute the block of code once. Otherwise we do not. COMP-202 - Programming with Iterations 45

Benefits of If Statements We can perform actions or commands some of the time but not all. Forces us to organize things : Certain events will only happen in one case. This creates a clear division. COMP-202 - Programming with Iterations 46

Doing the same thing many times Sometimes, we will want to execute the same block of code many times. How can we do that? COMP-202 - Programming with Iterations 47

Copy / Paste The naïve thing to do is copy paste your code. What are some problems with this? COMP-202 - Programming with Iterations 48

Copy / Paste 1)Annoying : Who wants to copy / paste that much 2)Error prone : Easy to make a mistake 3)Difficult to maintain : Hard to edit or fix mistakes (you have to edit the same code many times which can lead to more errors) 4)What if you don't know ahead of time how many steps you need? COMP-202 - Programming with Iterations 49

while loops In Java, we can create a while loop. A while loop is a statement that defines a block of code that continues to execute until a condition is false. COMP-202 - Programming with Iterations 50

if statement vs while loop if (condition) { //block of code //Go here //no matter what while (condition) { //block of code //Go here //only after //condition is false COMP-202 - Programming with Iterations 51

Syntax difference Syntactically, the only difference between a while loop and an if statement is the word while instead of if. The effect of this change is that the block of code continues to be repeated as long as condition is evaluated to be true. COMP-202 - Programming with Iterations 52

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; COMP-202 - Programming with Iterations 53

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; The purpose of the variable x here is to act as a loop counter It keeps track of how many times the loop has executed COMP-202 - Programming with Iterations 54

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; Initially, we set the variable x equal to 0. This means the first time we check the condition x < 4, the condition is true, so we execute the loop body. COMP-202 - Programming with Iterations 55

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; Next, we execute the loop body, which first involves printing to the screen. COMP-202 - Programming with Iterations 56

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; The next command of the loop body is increment x. This gives x the value of 1. COMP-202 - Programming with Iterations 57

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; Once the loop body finishes at the, the condition is then rechecked. Since x = 1 and 1 < 4, the block of code happens again. COMP-202 - Programming with Iterations 58

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; This procedure happens 2 more times. On the 4 th step, we test the condition and x = 3. Then after printing and adding 1 to x, x is now 4. COMP-202 - Programming with Iterations 59

Example of a while loop int x = 0; while (x < 4) { System.out.println( I have to write + this over and over. ); x++; If x == 4, then the condition is false, so we exit the loop and resume the code after the loop block has finished. COMP-202 - Programming with Iterations 60

Definition: iteration An iteration is a single execution of the instructions in the loop body. The previous loop had 4 iterations. One each for x=0, x=1, x=2, x=3

Important Clarification The condition of the while loop is only evaluated 1 time per step or iteration of the loop right before the block of code executes. The significance of this is if the condition changes inside the loop, the loop will keep going. COMP-202 - Programming with Iterations 62

Important Clarification int x = 0; while (x < 4) { x = x + 10; System.out.println( x is now 10 ); x = x - 10; x++; COMP-202 - Programming with Iterations 63

Important Clarification int x = 0; while (x < 4) { x = x + 10; System.out.println( x is now 10 ); x = x - 10; x++; Although x = 10 at this point, the loop condition is not tested until later, when x=1 again COMP-202 - Programming with Iterations 64

Practice Exercise: Figure out what the following loop does. int i = 0; while (i < 100) { if ( i % 3 == 0) { System.out.println(i); i++; COMP-202 - Programming with Iterations 65

What will this loop do? int x = 0; while (x < 4) { System.out.println(x); COMP-202 - Programming with Iterations 66

It goes on forever! The above is what is known as an infinite loop It will go on forever because we never change the value of x, which will always be less than 4 We will keep printing 0 to the screen. This is known as an infinite loop COMP-202 - Programming with Iterations 67

Tangent: Halting Problem (1) Alan Turing investigated the problem of: Given a computer program, can you detect if there is an infinite loop in it. He proved that you can not write a computer program to test definitively whether any computer program has an infinite loop. You'll know if the program ends, but not if it has an infinite loop COMP-202 - Programming with Iterations 68

Tangent: Halting Problem (2) This seems like a useless thing to prove, but it has consequences: 1)Philosophically, computers can't solve everything 2)Sometimes, we can take a more useful problem and prove that we can't solve it either, because if we could, then we'd be able to solve the Halting Problem COMP-202 - Programming with Iterations 69

One command while loops Like if statements, if you put a command following the while loop without a {, it will only include 1 line in your loop. -A very bad thing to do: int x = 0; while (x < 4); { // this is an infinite loop now! x++ COMP-202 - Conditional Programming 70

How many iterations does the following loop consist of? int x = 4; while (x > 4) { System.out.println( I have to write + this over and over. ); x++;

How many iterations does the following loop consist of? int x = 4; while (x > 4) { System.out.println( I have to write + this over and over. ); x++; 0 iterations because x is not > 4 at the beginning

How many iterations does the following int x = 6; loop consist of? while (x > 4) { System.out.println( I have to write + this over and over. ); x--;

How many iterations does the following int x = 6; loop consist of? while (x > 4) { System.out.println( I have to write + this over and over. ); x--; 2 iterations : 1 for x = 6, 1 for x = 5

How many iterations does the following int x = 6; loop consist of? while (x > 4) { System.out.println( I have to write + this over and over. ); x++;

How many iterations does the following int x = 6; loop consist of? while (x > 4) { System.out.println( I have to write + this over and over. ); x++; Infinite! x starts out equal to 6, we check if it is less than

How many iterations does the following int x = 3; loop consist of? while (x < 11) { System.out.println( I have to write + this over and over. ); x += 2;

How many iterations does the following int x = 3; while (x < 11) { System.out.println( I have to write + this over and over. ); x += 2; 4 iterations: x=3, x=5, x=7, x=9 loop consist of?

Off-By-One Errors It is a common logical error or bug to write loop conditions that result in the loop body being executed one time too few, or one time too many You should always test your code to check that your loops conditions do not cause such errors. COMP-202 - Programming with Iterations 79

Off-By-One Errors Example //this code is supposed to print all positive //values of x up until 5: int x = 1; while (x < 5) { System.out.println(x); x++; COMP-202 - Programming with Iterations 80

Off-By-One Errors Example The problem is the last iteration is x = 4. We should change the condition to: (x <= 5) OR (x < 6) COMP-202 - Programming with Iterations 81

Off-By-One Errors Tips To avoid off by one errors, you should always manually confirm the first step of a loop as well as the last step of a loop. Make sure the numbers are what you are expecting. COMP-202 - Programming with Iterations 82

General loop tips Try to think of exactly what it is that you want to do over and over again Figure out the range of values you want to try again and again. Is the loop counter also used in the computation? Make sure that your loop starts or initializes with the right result Make sure that your loop terminates with the correct result COMP-202 - Programming with Iterations 83

xample: Print every integer from 1 to n int i = 1; while (i <= n) { System.out.println(i); i++; COMP-202 - Programming with Iterations 84

Example: Performing the same code n times If you have code that you want to perform a fixed number of times, one way to do that is with a while loop and a counter: int counter = 0; while (counter < n) { //whatever you want done counter++; COMP-202 - Programming with Iterations 85

Exercise: While loop In unit 3, we looked at an example where we wanted to read 10 numbers and convert all of them from Fahrenheit to Celcius. Write a program using a while loop that reads 10 numbers from the keyboard, converts them one at a time to Fahrenheit, and prints the result to the screen. (Answers on next slide: no peaking!) COMP-202 - Programming with Iterations 86

import java.util.scanner; public class FahrenheitConverter { public static final double NUM_CONVERSIONS = 10; public static void main(string[] args) { int i = 0; Scanner reader = new Scanner(System.in); while (i < NUM_CONVERSIONS) { System.out.println(convertToCelcius(reader.nextInt())); i++; public static double converttocelcius(double fahrenheit){ return (fahrenheit 32.0) * 5.0 / 9.0; COMP-202 - Programming with Iterations 87

art 2: Class Variables and Constants

Class Constants (final) Very often, you will have a constant that you want to use throughout your entire class in many different methods. -Improves readability -Avoid errors -Easier to maintain Remember that we can declare a constant the same way as a variable, except we add the word final before the type. COMP-202 - Programming with Iterations 89

Class Constants (final) Sometimes, you'll declare a constant inside a method as normal, but you can also declare a final static constant outside of any method, but inside of a class: public class ConstantExample { public static final int NUM_STATES = 50; public static final int NUM_PROVINCES = 10; public static void main(string[] args) {... COMP-202 - Programming with Iterations 90

Class Constants (final) Now, throughout you code you won't have mysterious magic numbers like 50 and 10 throughout your code. It's easier to say for sure which 50's refer to the number of states and which 50's refer to something entirely different. Also will be much easier if the constant changes over time for whatever reason. COMP-202 - Programming with Iterations 91

Scope of variables and constants Remember, that any time you create a variable or constant, it's scope is only within the block of code it was declared in. This means that anywhere inside that block of code, the variable or constant is available and outside the block it is not. COMP-202 - Programming with Iterations 92

Scope of variables and constants public class CustomerService { public static final String COMPANY_NAME = Videotron ; public static void answercall() { System.out.print( Your call is very important to us. +Please stay on the line and a ); System.out.println( COMPANY_NAME + representative will be with your shortly ); public static void humanpicksup() { System.out.print( You owe + COMPANY_NAME + money for random ); System.out.println( surcharges. We hope you'll continue to enjoy our service. ); waitforswearing(); //The identifier COMPANY_NAME is now available throughout your entire class // CustomerService COMP-202 - Programming with Iterations 93

Scope of class variables public class Scope { public static String companyname = Videotron ;... Variables work the same way. This means that one thing you can do to share a variable between methods is create a variable outside of any method. In this case, you'll still want to write static. This is not generally good practice unless you know what you are doing! COMP-202 - Programming with Iterations 94

Class Variables These sorts of variables (or constants) are known as class variables (or class constants). They are called this because they belong to the entire class as opposed to one method. COMP-202 - Programming with Iterations 95

Example of bad use of class variables import java.util.scanner; public class BadFahrenheitConversion { public static double degrees = 0.0; public static Scanner reader = new Scanner(System.in); public static void main(string[] args) { degrees = reader.nextdouble(); converttocelcius(); System.out.println(degrees); public static void converttocelcius() { degrees = (degrees 32.0) * 5.0 / 9.0; COMP-202 - Programming with Iterations 96

Problems with this: Leads to bugs! 1)The variable degrees is used for different purposes (first it is fahrenheit then it is degrees) Confusing! 2)The method converttocelcius() has a side effect which is unexpected. 3)The code is not reusable. What if you copied this into a different program that already had a variable degrees defined? 4)Because you are doing 2 things with 1 variable, the print statement could be separated from when the value is set. 5)reader can be used by a different method and the main() method wouldn't know. COMP-202 - Programming with Iterations 97

Better (no class variables) import java.util.scanner; public class BadFahrenheitConversion { public static void main(string[] args) { Scanner reader = new Scanner(System.in); double fahrenheitdegrees = reader.nextdouble(); double celciusdegrees = converttocelcius(fahrenheitdegrees); System.out.println(celciusDegrees); public static double converttocelcius(double degrees) { return (degrees 32.0) * 5.0 / 9.0; COMP-202 - Programming with Iterations 98

Static constants Static constants do not normally have this problem since their values don't change. There are still cases where it is better to pass a constant to a method rather than use it. We will see later on that there are indeed times to create static variables, but for starters we should not use static variables and should only use static constants with simple types (i.e. int, double, float, boolean, etc. String is OK too despite the capital S) COMP-202 - Programming with Iterations 99

Part 3: Top Down Programming

Example A prime number is a positive integer >= 2 whose only divisors are 1 and itself. Write a method that calculates whether a number is prime or not using a while loop. The method should take as input an int and return a boolean value of true if the number is prime and false otherwise. COMP-202 - Programming with Iterations 101

Steps to solve this: First, you should figure out the input and the output of the method. This is normally given in this course, sometimes in words, sometimes in Java terminology With this knowledge, you can write the method header. If this step is not easy, then you need to think about the problem more to understand what it is you are trying to solve! COMP-202 - Programming with Iterations 102

Steps to solve this: public static boolean isprime(int n) { COMP-202 - Programming with Iterations 103

Steps to solve this: The next thing to figure out is an algorithm to solve the problem. This is not always easy. In the case of prime numbers, how can we figure out if a number n is prime (if we were doing it by hand)? COMP-202 - Programming with Iterations 104

Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors of n), then n is not prime 3)If none of them divide n, then n is prime COMP-202 - Programming with Iterations 105

Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime The word every strongly implies you'll need some sort of loop. COMP-202 - Programming with Iterations 106

Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime The if means we'll need some sort of if statement. n not equals prime is our conclusion and in Java will translate to a return statement with the value false COMP-202 - Programming with Iterations 107

Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime One thing to be very careful of is that none means we have to check ALL of the numbers to make the conclusion. COMP-202 - Programming with Iterations 108

Now lets analyze each step in detai 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime We know how to do something for every number. We know the code for printing every number from 1 to n. We just have to modify it to go from 2 until n-1 and to do other stuff instead of print! COMP-202 - Programming with Iterations 109

Steps to solve this: 1)Check every number from 2 up until n 1. 2)If any of these numbers evenly divide n (i.e. are factors), then n is not prime 3)If none of them divide n, then n is prime How can we check if a number x evenly divides n? COMP-202 - Programming with Iterations 110

Steps to solve this: How can we check if a number x evenly divides n? 1)Use int division. If x / n * n is equal to x, then x must be a multiple of n. Otherwise, we'd have lost information on the division. ex: 6 / 3 * 3 = 6 (6 is a multiple of 3) 5 / 3 * 3 = 3 (since 5 / 3 = 1 in integer division) 2)Use modulo % operator. x % n == 0 if x is a multiple of n. (ex: 48 hours after midnight is 0:00, since 48 is a multiple of 24) COMP-202 - Programming with Iterations 111

Solution public static boolean isprime(int n) { int x = 2; while (x < n) { if (n % x == 0) { return false; x++; return true; COMP-202 - Programming with Iterations 112

Even better solution public static boolean isprime(int n) { if (n < 2) { return false; int x = 2; while (x < n) { if (n % x == 0) { return false; x++; return true; COMP-202 - Programming with Iterations 113

Careful not to make this mistake! public static boolean isprime(int n) { if (n < 2) { return false; int x = 2; while (x < n) { if (n % x == 0) { return false; else { return true; x++; COMP-202 - Programming with Iterations 114

Careful not to make this mistake! public static boolean isprime(int n) { if (n < 2) { return false; int x = 2; while (x < n) { if (n % x == 0) { return false; else { return true; /* This code returns true if the first number for x (2) isn't a factor of n*/ x++; COMP-202 - Programming with Iterations 115

Top Down Programming The way we solved this problem is using a technique called topdown programming. We started out with a big goal (determine if a number is prime) Then we looked at the various steps we needed to solve that. (loop through all numbers, check conditions, return statement) We then examined how to solve those various steps (counter + while loop, % operator) COMP-202 - Programming with Iterations 116

Exercise Now that you have a method isprime, write another method printprimes. Your method should take as input an int n and return void. Your method should then print the first n prime numbers. When you write this method, for practice with taking an exam, try to write it on a piece of paper (or without seeing what the computer does). When you do this, call the method isprime(). But try not to think about how the method isprime() works. Focus only on what it does. COMP-202 - Programming with Iterations 117

Part 4: The for Statement

Common loop theme Very often in loops, one will do 3 things: 1)Perform some initialization before the loop starts. 2)Check a condition before an iteration of the loop starts. 3)Perform some finalization at the end of each iteration. COMP-202 - Programming with Iterations 119

Example loop int x = 0; //initialization while (x < 4) //condition { System.out.println(x); x++; //finalization at the end of each step COMP-202 - Programming with Iterations 120

for loop As this theme was so commonly used, Java added a for loop. A for loop is mostly the same as a while loop, but it adds as part of the for loop syntax an initialization and finalization step. for (initialization; condition; finalization) { //loop body COMP-202 - Programming with Iterations 121

for loop for (initialization; condition; finalization) { //loop body The initialization step happens once per loop. It happens right before the first step of the for loop COMP-202 - Programming with Iterations 122

for loop for (initialization; condition; finalization) { //loop body The condition is checked before each iteration of the loop. This is the same as in a while loop. COMP-202 - Programming with Iterations 123

for loop for (initialization; condition; finalization) { //loop body The finalization happens at the very end of every iteration of the loop. COMP-202 - Programming with Iterations 124

for loop for (int i = 0; i < 4; i++) { System.out.println(i); This does the same as the while loop prior. It prints the numbers 0,1,2,3 COMP-202 - Programming with Iterations 125

for loop vs while loop for (int i = 0; i < 4; i++) { System.out.println(i); int i = 0; while (i < 4) { System.out.println(i); i++; COMP-202 - Programming with Iterations 126

Benefit of for loop for loops are more readable than while loops in some cases. For example, in the previous case, it is obvious when looking at the statement int i = 0; that the statement is part of the loop. In the case of the while loop it isn't as obvious. COMP-202 - Programming with Iterations 127

Accidental error in while loop int x = 0; while (x < 4) { System.out.println(x); x++; Here it is not quite as obvious that int x = 0; is related to the loop. This means you or someone else could carelessly separate the 2 parts and cause a mistake (for example while copying and pasting) COMP-202 - Programming with Iterations 128

Benefit of while loop Typically, one chooses a while loop over a for loop if there is an indefinite number of iterations one wants to execute. For example, if you wanted to continue to do something until a certain event occurs. This translates better with a while loop because you don't have a loop counter anyway. COMP-202 - Programming with Iterations 129

Benefit of while loop int lastleafcupchampionship = 1967; while (lastleafcupchampionship == 1967) { System.out.println( Wow, even the Rangers are better. ); COMP-202 - Programming with Iterations 130

Infinite loop? int lastleafcupchampionship = 1967; while (lastleafcupchampionship == 1967) { System.out.println( Wow, even the Rangers are better. ); COMP-202 - Programming with Iterations 131

Treating a for loop like a while loop The statements in a for loop header can be anything including the empty statement: int x = 0; for (; x < 4; ) { System.out.println(x); x++; COMP-202 - Programming with Iterations 132

COMP-202 - Programming with Iterations 133

Exercise: Rewrite the isprime() method that we wrote to use a for loop instead of a while loop. Rewrite the printprimes() method as well. COMP-202 - Programming with Iterations 134

Part 5: Nested Loops

Nested Loops Sometimes, we will put a loop inside of a loop. When this happens...sometimes our brain is tied in a bit of a knot (buda-dum-dum-chi) COMP-202 - Programming with Iterations 136

Example : Print coordinate table Suppose we want to print all non-negative combinations of x and y in a grid. We can use 1 for loop inside another to do this. COMP-202 - Programming with Iterations 137

Example : Print coordinate table First, think about y being fixed. For any given y, if I want to print a range of x's, I can do this using a for loop. int y = 1; for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); COMP-202 - Programming with Iterations 138

Example : Print coordinate table int y = 1; for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); We know that this code will loop over x from 0 up until and including 9, and print: (1,0), (1,1), (1,2), (1,3), (1,4), (1,5), (1,6), (1,7), (1,8), (1,9) COMP-202 - Programming with Iterations 139

Example : Print coordinate table Now, I want to do this for every y from 0 to 10 as well. So we need to replace the y = 1 part with a loop that changes the value of y. COMP-202 - Programming with Iterations 140

Example : Print coordinate table for (int y = 0; y < 10; y++) { for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); COMP-202 - Programming with Iterations 141

Using constants for (int y = 0; y < 10; y++) { for (int x = 0; x < 10; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); It's better to replace the number 10 with a constant describing why we are using the number 10. It may be as simple as NUM_Y_COORDS, but it should be something COMP-202 - Programming with Iterations 142

Using constants final int VERTICAL_SIZE = 10; //could also be class constants? final int HORIZONTAL_SIZE = 10; for (int y = 0; y < VERTICAL_SIZE; y++) { for (int x = 0; x < HORIZONTAL_SIZE; x++) { System.out.print( ( + y +, + x + ), ); System.out.print( \n ); COMP-202 - Programming with Iterations 143

Exercise: Rewrite the above code using: 1)a while loop on the outside and a for loop on the inside 2)a for loop on the outside and a while loop on the inside 3)2 while loops COMP-202 - Programming with Iterations 144