Handout 4 Conditionals. Boolean Expressions.

Similar documents
Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Topics. Chapter 5. Equality Operators

Lesson 7 Part 2 Flags

Chapter 3. Selections

Flow of Control. Chapter 3

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

Flow of Control. Chapter 3

Introduction to Programming Using Java (98-388)

Controls Structure for Repetition

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

Chapter 4: Control Structures I

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

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

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

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

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

Java Flow of Control

CONDITIONAL EXECUTION: PART 2

Conditionals and Loops

JAVA OPERATORS GENERAL

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

BRANCHING if-else statements

Computational Expression

Lecture 5 Tao Wang 1

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

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

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Final Exam Practice. Partial credit will be awarded.

Getting started with Java

Programming with Java

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

COMP Flow of Control: Branching 2. Yi Hong May 19, 2015

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

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

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

PROGRAMMING FUNDAMENTALS

Full file at

Control Structures: if and while A C S L E C T U R E 4

Java is an objet-oriented programming language providing features that support

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

13 th Windsor Regional Secondary School Computer Programming Competition

Course Outline. Introduction to java

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

Darrell Bethea May 25, 2011

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

Conditional Execution

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

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Logic & program control part 2: Simple selection structures

Conditional Programming

Repetition CSC 121 Fall 2014 Howard Rosenthal

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Chapter 2: Basic Elements of Java

CMPT 125: Lecture 4 Conditionals and Loops

Question: Total Points: Score:

Question: Total Points: Score:

Loops. CSE 114, Computer Science 1 Stony Brook University

Java Bytecode (binary file)

AP COMPUTER SCIENCE A

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

AP Computer Science Unit 1. Programs

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 4: Control Structures I (Selection)

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

Repetition Structures

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

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

COMP Primitive and Class Types. Yi Hong May 14, 2015

CS 101 Spring 2007 Midterm 2 Name: ID:

Question: Total Points: Score:

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

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

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

Lecture 3 Tao Wang 1

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

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Full file at

The Java language has a wide variety of modifiers, including the following:

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Introduction to Java Unit 1. Using BlueJ to Write Programs

Question: Total Points: Score:

Introduction to Computer Science Midterm 3 Fall, Points

Midterms Save the Dates!

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

Operators in java Operator operands.

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

CS 106 Introduction to Computer Science I

Flow of Control. Chapter 3

Chapter 2: Using Data

CS111: PROGRAMMING LANGUAGE II

CS11 Java. Fall Lecture 1

Java I/O and Control Structures

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Algorithms and Conditionals

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Transcription:

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 1 of 8 Handout 4 Conditionals. Boolean Expressions. Example Problem. Write a program that will calculate and print bills for the city power company. The rates vary depending on whether the use is residential, commercial or industrial. A code of R means residential use, a code of C means commercial use and a code of I means industrial use. Any other code should be treated as an error. The rates are as follows: Residential: $6.00 plus $0.052 per kwh used Commercial: $60.00 for the first 1000 kwh and $0.045 for each additional kwh Industrial: When the consumption is below 5000 kwhs, o $76.00 for first 1000 kwh and $0.028 for each additional kwh Otherwise, o $270.00 for first 3000 kwh and $0.03 for each additional kwh Your program should prompt the user to enter an integer account number, the use code (type char), and the necessary consumption figures in kilowatt-hours. Your program should print the amount due from the user. Design: specify Input: Output: Data: Algorithm: - 1 -

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 2 of 8 /* Computes the amount due to the electrical company. Depending * on the customer type, various rules and rates are applied */ public class ElectricalBill { public static void main(string[] args) { // declare constants for different rates // commercial customer final int COM_LIMIT = 1000; final double COM_RATE = 0.045; final double COM_FEE = 60; // residential customer final double RES_RATE = 0.052; final double RES_FEE = 6; // industrial customer final int IND_LIMIT = 5000; final int IND_LIMIT_2 = 1000; final int IND_LIMIT_3 = 3000; final double IND_RATE_BELOW = 0.028; final double IND_FEE_BELOW = 76; final double IND_RATE_ABOVE = 0.03; final double IND_FEE_ABOVE = 270; // get user input. Scanner kb = new Scanner (System.in); - 2 -

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 3 of 8 Conditional statements are used to select a course of action based on the value of a specified condition. Java's conditional statements are. if-else statement if statement switch statement A condition often uses one of Java's equality operators or relational operators, which all return boolean results (true or false): == equal to > greater than!= not equal to < less than <= less than or equal to >= greater than or equal to equals(), equalsignorecase() methods for Strings, and other methods and expressions. Note the difference between the equality operator (==) and the assignment operator (=) Also note the difference in comparing two strings with == versus the equals() method. The first compares the references, the second compares the actual content of the strings. Syntax of if-else conditional statement: if ( condition ) { if-block else { else-block { s can be dropped around an if- or an else-block when it consists of just one statement. Examples: if(time < limit) System.out.println( You made it. ); else System.out.println( You missed the deadline. ); System.out.println( Bye! ); - 3 -

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 4 of 8 Nested conditionals: if(time < limit){ System.out.println( You made it. ); if (limit time >= 10 ) bonus = 100; else bonus = 50; else{ System.out.println( You missed the deadline. ); bonus = 0; Short version: no else clause: if ( condition ) { if-block or if ( condition ) if-block; in case the if-block only consists of one statement. Examples: delta = 0; if (sum > MAX) { delta = sum - MAX; System.out.println ("The sum is " + sum); Suppose sum = 50, MAX = 30. What will be the value of delta? What if sum = 20, MAX = 30 // Multibranch selection: if(score >= 90) grade = A ); else if (score >= 80) grade = B ; else if (score >= 70) grade = C ; else if (score >= 60) grade = D ; else grade = F ; - 4 -

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 5 of 8 Practice problem The user will enter a string containing a phone number preceded by the @ sign, as, for example, in the following line Don t hesitate to reach me @781-236-9978. Thanks! Display message Boston area code if the area code of the phone number is 617. - 5 -

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 6 of 8 3. Boolean (logical) operators: used to form complex conditions.! Logical NOT && Logical AND Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) Rules: The logical NOT expression negates the argument. if some boolean condition a is true, then!a is false; if a is false, then!a is true The logical AND expression a && b otherwise The logical OR expression a b otherwise is true if both a and b are true, and false is true if a or b or both are true, and false Precedence: NOT(!) is evaluated first, then AND(&&), then OR ( ). Examples: Find a value of n that will result in the execution of the if-block; else-block if (n % 2 == 0 && n > 5 n <= 3) { x = 35; else { x = 20; Identify one set of values of the variables and constants below that will result in the execution of the printing statement. // note: type of found is Boolean boolean found; if (total < MAX+5 &&!found) { System.out.println ("Processing"); - 6 -

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 7 of 8 Practice problems: 1. Modify your solution to the Boston area code practice problem to report Boston are code if the area code is either 617 or 781. 2. Assume variable yearhired stores the year an employee was hired. Write a code segment that prints found if the yearhired is in 1990 s but is not one of 1992 or 1993. 3. Assuming str1 and str2 are two variables of type String, write a code segment that would print one if str1 and str2 store the identical strings, two if they are not identical, but start with the same letter, and three in case they end with the same letter. - 7 -

Handout 4 cs180 - Programming Fundamentals Fall 17 Page 8 of 8 4. Another way to program multibranch selection Switch statement: syntax switch(controlling_expression) { case Case_Label_1: statements case Case_Label_2: statements default: statements Example: // seatlocationcode is an int variable switch(seatlocationcode) { case 15: System.out.println( Orchestra ); price = 40.00; case 17: System.out.println( Mezzanine ); price = 30.00; case 19: System.out.println( Balcony ); price = 15.00; default: System.out.println( Unknown seat code ); Controlling_Expression must be char, int, short or byte (or String since Java 7) Controlling Expression and Case_Label must have the same type When a break statement is encountered, control goes to the first statement after the switch. - 8 -