Advanced if/else & Cumulative Sum

Similar documents
Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Lecture 4: Conditionals

Topic 12 more if/else, cumulative algorithms, printf

CSc 110, Autumn 2016 Lecture 10: Advanced if/else; Cumulative sum. Adapted from slides by Marty Stepp and Stuart Reges

Topic 12 more if/else, cumulative algorithms, printf

CSS 161 Fundamentals of Compu3ng. Flow control (2) October 10, Instructor: Uma Murthy

Building Java Programs

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Returns & if/else. Parameters and Objects

Building Java Programs Chapter 4

Building Java Programs

Topic 11 Scanner object, conditional execution

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Topic 11 Scanner object, conditional execution

CSc 110, Autumn Lecture 13: Cumulative Sum and Boolean Logic. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Autumn 2016 Lecture 12: Advanced if/else; Cumulative sum. Adapted from slides by Marty Stepp and Stuart Reges

Building Java Programs

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

Building Java Programs

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

CS 101 Spring 2007 Midterm 2 Name: ID:

Lecture 5: Methods CS2301

Topic 21 arrays - part 1

Computational Expression

Building Java Programs

CONDITIONAL EXECUTION

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

Controls Structure for Repetition

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

CompSci 125 Lecture 11

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

Topic 14 while loops and loop patterns

Building Java Programs

! 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

Topic 5 for loops and nested loops

Building Java Programs

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

AP Computer Science. if/else, return values. Copyright 2010 by Pearson Education

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

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Midterm Review Session

Principles of Computer Science

CS 106A, Lecture 5 Booleans and Control Flow

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

Programming with Java

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

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

Flow Control. Key Notion. Statement Categories. 28-Oct-10

assertion: A statement that is either true or false.

Loops. CSE 114, Computer Science 1 Stony Brook University

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

CS 112 Introduction to Programming

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Conditional Execution

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.

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

Building Java Programs A Back to Basics Approach 4th Edition Reges TEST BANK Full download at:

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

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

Chapter 2: Basic Elements of Java

Example: Monte Carlo Simulation 1

CS-201 Introduction to Programming with Java

Chapter 3. Selections

4. Java Project Design, Input Methods

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

Loops and Expression Types

Recap: Assignment as an Operator CS 112 Introduction to Programming

Static Methods & Decomposition

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

Repetition Structures

1. An operation in which an overall value is computed incrementally, often using a loop.

The for Loop. Lesson 11

COMP 202 Java in one week

CS 112 Introduction to Programming

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

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

Chapter 4: Control Structures I

FLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

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

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Selections. CSE 114, Computer Science 1 Stony Brook University

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

COMP 202. Java in one week

Building Java Programs

Topic 4 Expressions and variables

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

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

Java Coding 3. Over & over again!

Arithmetic Compound Assignment Operators

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

Transcription:

Advanced if/else & Cumulative Sum Subset of the Supplement Lesson slides from: Building Java Programs, Chapter 4 by Stuart Reges and Marty Stepp (http://www.buildingjavaprograms.com/ )

Questions to consider What are the advantages of using Returns? What do we have to consider when returning a value in a series of nested if/else s? What additional Operators do we need to make our if conditions (tests) more useful? 2

if/else with return // Returns the larger of the two given integers. public static int max(int a, int b) { if (a > b) { return a; else { return b; Methods can return different values using if/else Whichever path the code enters, it will return that value. Returning a value causes a method to immediately exit. All paths through the code must reach a return statement. 3

All paths must return public static int max(int a, int b) { if (a > b) { return a; // Error: not all paths return a value The following also does not compile: public static int max(int a, int b) { if (a > b) { return a; else if (b >= a) { return b; The compiler thinks if/else/if code might skip all paths, even though mathematically it must choose one or the other. 4

if/else, return question Write a method quadrant that accepts a pair of real numbers x and y and returns the quadrant for that point: y+ quadrant 2 quadrant 1 x- x+ quadrant 3 quadrant 4 y- Example: quadrant(-4.2, 17.3) returns 2 If the point falls directly on either axis, return 0. 5

Logic 6

Logical operators Tests can be combined using logical operators: Operator Description Example Result && and (2 == 3) && (-1 < 5) or (2 == 3) (-1 < 5) false true! not!(2 == 3) true "Truth tables" for each, used with logical values p and q: p q p && q p q true true true true true false false true false true false true false false false false p!p true false false true 7

Evaluating logic expressions Relational operators have lower precedence than math. 5 * 7 >= 3 + 5 * (7-1) 5 * 7 >= 3 + 5 * 6 35 >= 3 + 30 35 >= 33 true Relational operators cannot be "chained" as in algebra. 2 <= x <= 10 true <= 10 (assume that x is 15) error! Instead, combine multiple tests with && or 2 <= x && x <= 10 true && false false 8

Logical questions What is the result of each of the following expressions? int x = 42; int y = 17; int z = 25; A: y < x && y <= z B: x % 2 == y % 2 x % 2 == z % 2 C: x <= y + z && x >= y + z D:!(x < y && x < z) E: (x + y) % 2 == 0!((z - y) % 2 == 0) Answers: A: true, B: false, C: true, D: true, E:false 9

if/else, return question Write a method quadrant that accepts a pair of real numbers x and y and returns the quadrant for that point: y+ quadrant 2 quadrant 1 x- x+ quadrant 3 quadrant 4 y- Example: quadrant(-4.2, 17.3) returns 2 If the point falls directly on either axis, return 0. 10

if/else, return answer public static int quadrant(double x, double y) { if (x > 0 && y > 0) { return 1; else if (x < 0 && y > 0) { return 2; else if (x < 0 && y < 0) { return 3; else if (x > 0 && y < 0) { return 4; else { // at least one coordinate equals 0 return 0; 11

Code Sample Example Write a method daysinmonth that accepts an integer representing the month and returns the number of days in that month. Assume there are no leap years Examples: daysinmonth(2) returns 28 daysinmonth(5) returns 31 12

Cumulative algorithms

Cumulative? What does cumulative mean? To increase by successive additions. Accumulation. What kind of problems are solved accumulating values? Series, summation for averages, approximation for Pi, etc. What does any cumulative activity start with? An initial value (that s key!) 14

Adding many numbers How would you find the sum of all integers from 1-1000? // This may require a lot of typing int sum = 1 + 2 + 3 + 4 +... ; System.out.println("The sum is " + sum); What if we want the sum from 1-1,000,000? Or the sum up to any maximum? How can we generalize the above code? 15

Cumulative sum loop int sum = 0; for (int i = 1; i <= 1000; i++) { sum = sum + i; System.out.println("The sum is " + sum); cumulative sum: A variable that keeps a sum in progress and is updated repeatedly until summing is finished. The sum in the above code is an attempt at a cumulative sum. Cumulative sum variables must be declared outside the loops that update them, so that they will still exist after the loop. 16

Cumulative product This cumulative idea can be used with other operators: int product = 1; for (int i = 1; i <= 20; i++) { product = product * 2; System.out.println("2 ^ 20 = " + product); How would we make the base and exponent adjustable? 17

Scanner and cumul. sum We can do a cumulative sum of user input: Scanner console = new Scanner(System.in); int sum = 0; for (int i = 1; i <= 100; i++) { System.out.print("Type a number: "); sum = sum + console.nextint(); System.out.println("The sum is " + sum); What if we wanted to first specify how many values are to be read in and then also print out the average of the values? Let s code this... 18

Factoring if/else code factoring: Extracting common/redundant code. Can reduce or eliminate redundancy from if/else code. Example: if (a == 1) { System.out.println(a); x = 3; b = b + x; else if (a == 2) { System.out.println(a); x = 6; y = y + 10; b = b + x; else { // a == 3 System.out.println(a); x = 9; b = b + x; System.out.println(a); x = 3 * a; if (a == 2) { y = y + 10; b = b + x; 19