Condi(onals and Loops

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

1.3 Conditionals and Loops

CS 112 Introduction to Programming

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

1.3 Conditionals and Loops

1.3 Conditionals and Loops

Variables and Control Structures. CS 110 Eric Eaton

1.3 Conditionals and Loops

1.3 Conditionals and Loops

! Sequence of statements that are actually executed in a program. ! Conditionals and loops: enable us to choreograph control flow.

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

Repetition, Looping. While Loop

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

CONDITIONAL EXECUTION

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

3. Conditionals & Loops

3. Conditionals and loops

Conditionals, Loops, and Style

Classes and objects. Chapter 2: Head First Java: 2 nd Edi4on, K. Sierra, B. Bates

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

CSEN 202 Introduction to Computer Programming

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

CONDITIONAL EXECUTION: PART 2

Learning Outcomes for this week. Inf1-OP. A Foundation for Programming. A Foundation for Programming

CS111: PROGRAMMING LANGUAGE II

Loops. CSE 114, Computer Science 1 Stony Brook University

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

3. Conditionals & Loops

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Computer Programming I - Unit 5 Lecture page 1 of 14

if Statement Numeric Rela5onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Object-Oriented Programming

if Statement Numeric Rela7onal Operators The if Statement Flow of Control: Branching (Savitch, Chapter 3)

Lecture 3: Loops. While Loops. While Loops: Newton-Raphson Method. While Loops: Powers of Two

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

Variables and data types

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

AP Programming - Chapter 6 Lecture

Lecture 5: Methods CS2301

CIS 110 Introduction To Computer Programming. February 29, 2012 Midterm

Programming Logic and Design Sixth Edition

Java Basic Programming Constructs

CHAPTER 5 FLOW OF CONTROL

Lecture 3: Loops. While Loops. While Loops: Powers of Two. While Loops: Newton-Raphson Method

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

Repetition, Looping CS101

2.3 Flow Control. Flow-Of-Control. If-Else: Leap Year. If-Else

CONDITIONAL EXECUTION

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Introduction to the Java Basics: Control Flow Statements

AP CS Unit 3: Control Structures Notes

Course Outline. Introduction to java

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

A Foundation for Programming

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

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

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

Chapter 4: Conditionals and Recursion

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

CS1150 Principles of Computer Science Loops (Part II)

CSE 114 Computer Science I

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

Other conditional and loop constructs. Fundamentals of Computer Science Keith Vertanen

Chapter 4 Introduction to Control Statements

Principles of Computer Science

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

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

Programming in the Small II: Control

D0010E Object- oriented programming and design. Today. Today An introduc<on to the basic syntax and seman<cs of Java

Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park

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

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

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

Sequential Search (Searching Supplement: 1-2)

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

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

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

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

LEC03: Decisions and Iterations

A Founda4on for Programming

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

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

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

Unit 1 Lesson 4. Introduction to Control Statements

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

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Pace University. Fundamental Concepts of CS121 1

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

Java Bytecode (binary file)

CS 106 Introduction to Computer Science I

Assignment 2.4: Loops

A Beginner s Guide to Programming Logic, Introductory. Chapter 6 Arrays

COMP-202 Unit 4: Programming with Iterations

Lecture 1 Java SE Programming

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

Transcription:

Condi(onals and Loops 1

Review Primi(ve Data Types & Variables int, long float, double boolean char String Mathema(cal operators: + - * / % Comparison: < > <= >= == 2

A Founda(on for Programming any program you might want to write objects func(ons and modules graphics, sound, and image I/O arrays condi(onals and loops Math primi(ve data types text I/O assignment statements last lecture: equivalent to a calculator 3

A Founda(on for Programming any program you might want to write objects func(ons and modules graphics, sound, and image I/O arrays condi(onals and loops Math primi(ve data types text I/O assignment statements 4

Control Flow Programs execute one statement axer another Condi(onals and loops allow us to control the flow statement 1 boolean 1 true false statement 2 statement 1 statement 3 boolean 2 true statement 2 false statement 4 statement 3 straight- line control flow control flow with condi(onals and loops 5

Anima(ons with PennDraw 6

The Infinite While Loop The infinite while loop: executes the loop body repeatedly Execute statement 1 Execute statement 2... Repeat statement 2 while (true) { statement 1; statement 2; loop body boolean expression true statement 1 7

What will this do? System.out.print( Program running );! while (true) {! System.out.print(. );!! System.out.println();! System.out.println( Program Exiting );! 8

Using PennDraw for anima(on PennDraw.enableAnima(on(10) Anima(on at 10 frames per second PennDraw.advance() PennDraw.disableAnima(on() 9

Using PennDraw for Anima(on public sta(c void main(string[] args) { PennDraw.setCanvasSize(500, 500); PennDraw.enableAnima(on(30); while (true) { // repeats forever // draw frame of anima(on (your code here) PennDraw.advance(); // display next frame 10

In- Class Demo: Bouncing Ball 11

Equa(ons of Mo(on (Simplified) s = displacement t = (me v = velocity a = accelera(on Constant accelera(on (a) s i+1 = s i + v i Δt v i+1 = v i + a Δt 12

In- Class Demo: Bouncing Ball 13

Condi(onals 14

If Statement The if statement: A common branching structure Evaluate a boolean expression If true, execute some statements If false, execute other statements boolean expression if (boolean expression) { //statement T; else { //statement F; can be any sequence of statements true statement T false statement F 15

How could we write a program to check if a number is even or odd? How do we provide a number to java? Command- line arguments args[0] is the first argument, args[1] the second argument and so on args[0] is a String 16

Command line arguments To run programs you have wripen so far java MyHouse java HelloWorld We d like to be able to provide informa(on at the command line java HelloWorld John want the program say Hello John as opposed to Hello World 17

Command line arguments public class Hello { public sta(c void main (String[] args) { String name = args[0]; System.out.println("Hello " + name); 18

Command line arguments args[0] will be a String How to convert a String to an integer? Integer.parseInt() 19

Back to even or odd detec(on Live coding. 20

Rela(onal Expressions < less than > is greater than <= is less than or equal to >= is greater than or equal to == is equivalent!= is not equivalent 21

Rela(onal Expressions: Examples 1. if ( true ) { 2. if ( 10 > 10 ) { 3. if ( 10 >= 10 ) { 4. if ( 'a' == 'a' ) { 5. if ( 'a'!= 'a' ) { 6. if ( Penn!= penn ) { 22

Logical Expressions && logical conjunc(on (and) both expressions must be true for conjunc(on to be true logical disjunc(on (or) either expression must be true for disjunc(on to be true! logical nega(on (not) true false, false true 23

Logical Expression Examples 1. if ( (2 > 1) && (3 > 4) ) { 2. if ( ( b == b ) && (1 + 2 == 3) ) { 3. if (!false ) { 4. if (!(1 < -1) ) { 5. if (!(10 < 20) false ) { 6. if (!(10 > 20) && (10 < 20) ) { 7. if ( (true false) && true ) { 8. if ( (true && false) true ) ) { 9. 24

If Statement The if statement: A common branching structure Evaluate a boolean expression If true, execute some statements If false, execute other statements 25

If Statement Ex. Take different ac(ons depending on the value of a variable public class Flip { public static void main(string[] args) { if (Math.random() < 0.5) { System.out.println("Heads"); else { System.out.println("Tails"); % java Flip Heads % java Flip Heads % java Flip Tails % java Flip Heads 26

If Statement Examples 27

In- Class Demo: Bouncing Ball 28

Condi(onals: if- else- if- statement if ( boolean_expression_1 ) { statements; else if ( boolean_expression_2 ) { statements; else if ( boolean_expression_3 ) { statements; else { statements; 29

Example: Graduated Income Tax Pay a certain income tax rate depending on income: Income Rate 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 174,700 311,950 33% 311,950-35% 5 mutually exclusive alterna(ves 30

Nested If Statements Use nested if statements to handle mul(ple alterna(ves if (income < 47450) rate = 0.22; else { if (income < 114650) rate = 0.25; else { if (income < 174700) rate = 0.28; else { if (income < 311950) rate = 0.33; else rate = 0.35; Income Rate 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 174,700 311,950 33% 311,950-35% 31

Nested If Statements Income Rate 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 174,700 311,950 33% 311,950-35% 5 mutually exclusive alterna(ves Alterna(ve shortened version: double rate; if (income < 47450) rate = 0.22; else if (income < 114650) rate = 0.25; else if (income < 174700) rate = 0.28; else if (income < 311950) rate = 0.33; else rate = 0.35; 32

Nested If Statements What is wrong with the following implementa(on? Income Rate 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 174,700 311,950 33% 311,950-35% double rate = 0.35; if (income < 47450) rate = 0.22; if (income < 114650) rate = 0.25; if (income < 174700) rate = 0.28; if (income < 311950) rate = 0.33; 5 mutually exclusive alterna(ves 33

Condi(onals: switch- statement Works like a if- else statement. Convenient for large numbers of value tests switch( expression ) { case label1: statements; break; case label2: statements; break; default: statements; // label1 equals expression // label2 equals expression // Nothing matches 34

public static void main(string[] args) { int month = Integer.parseInt(args[0]); String monthstring; switch (month) { case 1: monthstring = "January"; break; case 2: monthstring = "February"; break; case 3: monthstring = "March"; break; case 4: monthstring = "April"; break; case 5: monthstring = "May"; break; case 6: monthstring = "June"; break; case 7: monthstring = "July"; break; case 8: monthstring = "August"; break; case 9: monthstring = "September"; break; case 10: monthstring = "October"; break; case 11: monthstring = "November"; break; case 12: monthstring = "December"; break; default: monthstring = "Invalid month"; break; System.out.println(monthString); 35

+, -, *, / and An aside Operators i++; equivalent to i = i + 1; i += 2; equivalent to i = i + 2; i--; equivalent to i = i 1; i -= 3; equivalent to i = i - 3; i *= 2; equivalent to i = i * 2; i /= 4; equivalent to i = i / 4; i % 3; remainder axer i is divided by 3 (modulo) 36

Itera(on 37

Itera(on Repe((on of a program block Iterate when a block of code is to repeated mul(ple (mes. Op(ons The while- loop The for- loop 38

The While Loop 39

While Loop The while loop: A common repe((on structure Evaluate a boolean expression If true, execute some statements Repeat loop continuation condition statement 2 while (boolean expression) { statement 1; loop body statement 2; boolean expression false true statement 1 40

The Infinite While Loop, Re- examined System.out.print( Program running );! while (true) {! System.out.print(. );!! System.out.println();! System.out.println( Program Exiting );! 41

While Loop: Powers of Two Example: Print powers of 2 that are 2 N Increment i from 0 to N Double v each (me int i = 0; int v = 1; while (i <= N) { System.out.println(i + " " + v); i++; v = 2 * v; i v 0 1 1 2 2 4 3 8 4 16 5 32 Output: 0 1 1 2 2 4 3 8 4 16 N = 4 i <= N true true true true true false 42

While Loop Challenge Q: Is there anything wrong with the following code for prin(ng powers of 2? int i = 0; int v = 1; while (i <= N) System.out.println(i + " " + v); i = i + 1; v = 2 * v; 44

While Loop Challenge Q: Is there anything wrong with the following code for prin(ng powers of 2? int i = 0; int v = 1; while (i <= N) System.out.println(i + " " + v); i = i + 1; v = 2 * v; A: Need curly braces around statements in while loop otherwise it enters an infinite loop, prin(ng "0 1 45

The 3 Parts of a Loop int i = 1 ; initialization of loop control variable // count from 1 to 100 while ( i < 101 ) { test of loop termination condition System.out.println( i ) ; i = i + 1 ; modification of loop control variable 46

Example: Factorial int factorial = 1; while (mynumber > 0) { factorial *= mynumber; --mynumber; System.out.println(factorial); 47

Keyboard input PennDraw.hasNextKeyTyped() check to see if the user has pressed key If the user presses a key, PennDraw.hasNextKeyTyped() is true un(l and unless you write a line that processes the input c = PennDraw.nextKeyTyped(); 48

public class KeyboardInput { public static void main(string[] args) { char c = 0; double radius = 0.02; PennDraw.setCanvasSize(600, 600); PennDraw.enableAnimation(10); while (c!= 'q') { if (PennDraw.hasNextKeyTyped()) { c = PennDraw.nextKeyTyped(); PennDraw.circle(0.5, 0.5, radius); radius = radius + 0.02; PennDraw.advance(); 49

The For Loop Copyright 2004, FoxTrot by Bill Amend www.ucomics.com/foxtrot/2003/10/03 54

For Loops Handles details of the counter- controlled loop automa(cally The for loop structure includes: the ini(aliza(on of the the loop control variable, the termina(on condi(on test, and control variable modifica(on for (int i = 1; i < 101; i = i + 1) { initialization test modification 55

For Loop: Powers of Two Example: Print powers of 2 that are 2 N Increment i from 0 to N Double v each (me int v = 1; for (int i = 0; i <= N; i++) { System.out.println(i + " " + v); v = 2 * v; v 1 Output: 0 1 1 2 2 4 3 8 4 16 N = 4 i 0 i <= N true 2 1 true 4 2 true 8 3 true 16 4 true 32 5 false 56

For Loop Examples A for loop that counts from 0 to 9: // modify part can be simply i++ for ( i = 0; i < 10; i = i + 1 ) { System.out.println( i ) ; or we can count backwards by 2 s : // modify part can be i -= 2 for ( i = 10; i > 0; i = i - 2 ) { System.out.println( i ) ; 57

For loop examples compute a finite sum (1 + 2 + + N) int sum = 0; for (int i = 0; i <= N; i++) sum += i; System.out.println(sum); print largest power of two less than or equal to N int v = 0 ; for (v = 1; v <= N/2; v *= 2); System.out.println(v); 58

When Does a for Loop Initialize, Test and Modify? Just as with a while loop, a for loop initializes the loop control variable before beginning the first loop iteration performs the loop termination test before each iteration of the loop modifies the loop control variable at the very end of each iteration of the loop The for loop is easier to write and read for counter-controlled loops. 59

public static void main(string[] args){ PennDraw.setCanvasSize(500,500); double radius = 250.0; while ( radius > 1.0 ) { PennDraw.circle(0.5, 0.5, radius / 500); radius = radius - 5.0; public static void main(string[] args){ PennDraw.setCanvasSize(500,500); for ( double radius = 250.0; radius > 1.0; radius -= 5.0 ) { PennDraw.circle(0.5, 0.5, radius / 500); 60

The break & continue Statements The break & continue statements can be used in while and for loops to skip the remaining statements in the loop body: break causes the looping itself to abort continue causes the next turn of the loop to start In a for loop, the modification step will still be executed 62

Example: Break in a For-Loop int i; OUTPUT: for (i = 1; i < 10; i = i + 1) { if (i == 5) { 1 2 3 4 break; Broke out of loop at i = 5 System.out.println(i); System.out.println( \nbroke out of loop at i = + i); 63

Example: Continue in a For-Loop int i; for (i = 1; i < 10; i = i + 1) { if (i == 5) { continue; System.out.println(i); System.out.println( Done ); OUTPUT: 1 2 3 4 6 7 8 9 Done 64

Problem: Continue in While-Loop // This seems equivalent to for loop // in previous slide but is it?? int i = 1; while (i < 10) { if (i == 5) { continue; System.out.println(i); i = i + 1; System.out.println( Done ); OUTPUT:??? 65

Variable Scope Variable scope: That set of code statements in which the variable is known to the compiler Where it can be referenced in your program Limited to the code block in which it is defined A code block is a set of code enclosed in braces ({ ) One interesting application of this principle allowed in Java involves the for loop construct 66

Scoping and the For-Loop Index Can declare and initialize variables in the heading of a for loop These variables are local to the for-loop They may be reused in other loops int count = 1; for (int i = 0; i < 10; i++){ count *= 2; //using 'i' here generates a compiler error 67