Topic 12 more if/else, cumulative algorithms, printf

Similar documents
Topic 12 more if/else, cumulative algorithms, printf

Building Java Programs Chapter 4

Building Java Programs

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

Advanced if/else & Cumulative Sum

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

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

Topic 11 Scanner object, conditional execution

Building Java Programs

Building Java Programs

Topic 11 Scanner object, conditional execution

Building Java Programs

Building Java Programs

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

Returns & if/else. Parameters and Objects

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

Building Java Programs

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

Lecture 4: Conditionals

Building Java Programs

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

Topic 21 arrays - part 1

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.

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

Midterm Review Session

Building Java Programs

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

CS 112 Introduction to Programming

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

Midterm Examination (MTA)

Building Java Programs

Chapter 4: Control Structures I

Building Java Programs

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

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

Chapter 2: Basic Elements of Java

Topic 4 Expressions and variables

CS 112 Introduction to Programming

Sierpinski Valentine.

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

Building Java Programs

Topic 14 while loops and loop patterns

CSc 110, Autumn Lecture 11: Strings. Adapted from slides by Marty Stepp and Stuart Reges

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

Object Oriented Programming. Java-Lecture 1

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

CS 106A, Lecture 5 Booleans and Control Flow

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

Building Java Programs

CS 112 Introduction to Programming

Building Java Programs

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Sierpinski Valentine. q Our journey of introducing conditionals

CS 112 Introduction to Programming

1 Short Answer (10 Points Each)

assertion: A statement that is either true or false.

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

Building Java Programs

Building Java Programs Chapter 2

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

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Building Java Programs

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

Building Java Programs

Final. Your Name CS Fall 2014 December 13, points total Your Instructor and Section

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Lecture 2: Operations and Data Types

Topic 6 loops, figures, constants

Introduction to Computer Programming

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

Building Java Programs Chapter 2

Java Assignment 3: Loop Practice Ver 3.0 Last Updated: 12/1/2015 8:57 AM

Topic 7 parameters. Based on slides from Marty Stepp and Stuart Reges from

Example: Monte Carlo Simulation 1

Building Java Programs

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

CSE 303 Lecture 8. Intro to C programming

Conditional Execution

Topic 13 procedural design and Strings

printf( Please enter another number: ); scanf( %d, &num2);

Lecture 5: Methods CS2301

4 WORKING WITH DATA TYPES AND OPERATIONS

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

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

Building Java Programs

Structured Program Development in C

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.

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Control Flow Practice Problems Mr. Fahrenbacher AP Computer Science A

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

Controls Structure for Repetition

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

CS 101 Spring 2007 Midterm 2 Name: ID:

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

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

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

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

CEN 414 Java Programming

Transcription:

Topic 12 more if/else, cumulative algorithms, printf "We flew down weekly to meet with IBM, but they thought the way to measure software was the amount of code we wrote, when really the better the software, the fewer lines of code." -Bill Gates Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/

Clicker Question int x = 4; int y = 5; x = mystery(x, y); System.out.print(x + " " + y); y = mystery(x, x); System.out.print(" " + x + " " + y); public static int mystery(int x, int y) { x *= 3; y = x / y; return x + y; What is output by the code above when it is run? A. 4 5 4 5 B. 14 5 14 45 C. 14 5 14 5 D. 14 5 50 5 E. 14 5 14 50

Nested if/else Example: if (x > 0) { System.out.println("Positive"); else if (x < 0) { System.out.println("Negative"); else { System.out.println("Zero");

Which nested if/else? Whether you made the dean's list (GPA 3.8) or honor roll (3.5-3.8). nested if / else if Whether a number is divisible by 2, 3, and/or 5. sequential if / if / if Computing a grade of A, B, C, D, or F based on a percentage. nested if / else if / else if / else if / else

if/else with return The following two versions of a max method don't compile: public static int max(int a, int b) { if (a > b) { return a; // Error: not all paths return a value 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 some paths, even though mathematically it must choose one or the other.

All paths must return This version of max does compile and works: // Returns the larger of the two given integers. public static int max(int a, int b) { if (a > b) { return a; else { return b;

FORMATTING WITH PRINTF

Formatting text with printf System.out.printf("format string", parameters); A format string can contain placeholders to insert parameters: %d integer %f real number %s string these placeholders are used instead of concatenation (+) Example: int x = 3; int y = -17; System.out.printf("x is %d and y is %d!\n", x, y); // x is 3 and y is -17! printf does not insert a newline unless you add \n

printf width %Wd %-Wd %Wf... integer, W characters wide, right-aligned integer, W characters wide, left-aligned real number, W characters wide, right-aligned for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 10; j++) { System.out.printf("%4d", (i * j)); System.out.println(); // to end the line Output: 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30

printf precision %.Df %W.Df %-W.Df real number, rounded to D digits after decimal real number, W chars wide, D digits after decimal real number, W wide (left-align), D after decimal double gpa = 3.253764; System.out.printf("your GPA is %.1f\n", gpa); System.out.printf("more precisely: %8.3f\n", gpa); Output: your GPA is 3.3 more precisely: 3.254 8 3

Cumulative algorithms reading: 4.2

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 +... + 999 + 1000; 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?

A failed attempt An incorrect solution for summing 1-1000: for (int i = 1; i <= 1000; i++) { int sum = 0; sum = sum + i; // error: sum is undefined here System.out.println("The sum is " + sum); sum's scope is in the for loop, so the code does not compile. cumulative sum: A variable that keeps a sum in progress and is updated repeatedly until summing is finished. The sum above is an incorrect attempt at a cumulative sum.

Corrected cumulative sum int sum = 0; for (int i = 1; i <= 1000; i++) { sum = sum + i; System.out.println("The sum is " + sum); Cumulative sum variables must be declared outside the loops that update them, so that they will still exist after the loop.

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?

Cumulative sum question Modify the Receipt program from Ch 2 (tax 8%, tip 15%). Prompt for how many people, and each person's dinner cost. Use static methods to structure the solution. Example log of execution: How many people ate? 4 Person #1: How much did your dinner cost? 20.00 Person #2: How much did your dinner cost? 15 Person #3: How much did your dinner cost? 30.0 Person #4: How much did your dinner cost? 10.00 Subtotal: $ 75.00 Tax: $ 6.00 Tip: $ 11.25 Total: $ 92.25

Cumulative sum answer // This program enhances our Receipt program using a cumulative sum. import java.util.*; public class Receipt2 { public static void main(string[] args) { Scanner console = new Scanner(System.in); double subtotal = meals(console); results(subtotal); // Prompts for number of people and returns total meal subtotal. public static double meals(scanner console) { System.out.print("How many people ate? "); int people = console.nextint(); double subtotal = 0.0; // cumulative sum... for (int i = 1; i <= people; i++) { System.out.print("Person #" + i + ": How much did your dinner cost? "); double personcost = console.nextdouble(); subtotal = subtotal + personcost; // add to sum return subtotal;

printf answer (partial)... // Calculates total owed, assuming 8% tax and 15% tip public static void results(double subtotal) { double tax = subtotal *.08; double tip = subtotal *.15; double total = subtotal + tax + tip; System.out.printf("Subtotal: $%6.2f\n", subtotal); System.out.printf("Tax: $%6.2f\n", tax); System.out.printf("Tip: $%6.2f\n", tip); System.out.printf("Total: $%6.2f\n", total);