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

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

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

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

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

Condi(onals and Loops

CHAPTER 5 FLOW OF CONTROL

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

Decisions, Decisions, Decisions. GEEN163 Introduction to Computer Programming

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Programming Language. Control Structures: Selection (switch) Eng. Anis Nazer First Semester

Control Structures in Java if-else and switch

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

BRANCHING if-else statements

Boolean Data-Type. Boolean Data Type (false, true) i.e. 3/6/2018. The type bool is also described as being an integer: bool bflag; bflag = true;

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

CS1150 Principles of Computer Science Boolean, Selection Statements

Chapter 4: Control Structures I

Relational & Logical Operators, if and switch Statements

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

Lecture 4. CS118 Term planner. The simple if statement. Control flow: selection. The if... else statement cont... The if... else statement.

CHRIST THE KING BOYS MATRIC HR. SEC. SCHOOL, KUMBAKONAM CHAPTER 9 C++

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

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

Logical Operators and switch

Chapter 4 - Notes Control Structures I (Selection)

Information Science 1

Floating-point lab deadline moved until Wednesday Today: characters, strings, scanf Characters, strings, scanf questions clicker questions

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

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

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

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

Chapter 5 Conditional and Iterative Statements. Statement are the instructions given to the computer to perform any kind of action.

Chapter 2: Objects and Primitive Data

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

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

Datatypes, Variables, and Operations

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

Topics. Chapter 5. Equality Operators

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

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

Lecture 9. Monday, January 31 CS 205 Programming for the Sciences - Lecture 9 1

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

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures in Java if-else and switch

Topic 4 Expressions and variables

Boolean Algebra Boolean Algebra

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

Chapter 3 Selection Statements

Midterms Save the Dates!

Introduction to Computing Lecture 05: Selection (continued)

CIS 110: Introduction to Computer Programming

5. Control Statements

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

Building Java Programs

Decision Structures. Selection. Selection options (in Java) Plain if s (3 variations) Each action could be any of: if else (3 variations)

Operators. Java operators are classified into three categories:

Topic 5: Enumerated Types and Switch Statements

Algorithms and Conditionals

BBM 101 Introduc/on to Programming I Fall 2013, Lecture 4

2.8. Decision Making: Equality and Relational Operators

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

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

Chapter 8 Statement-Level Control Structures

Building Java Programs

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

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Conditionals. CSE / ENGR 142 Programming I. Chapter 4. Conditional Execution. Conditional ("if ") Statement. Conditional Expressions

CONDITIONAL EXECUTION

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.

CS 112 Introduction to Programming

CS 112 Introduction to Programming

10/9/2012. Comparison and Logical Operators The if Statement The if else Statement Nested if Statements The switch case. switch case Statement

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Lecture 4: Conditionals

Decision Structures. Lesson 03 MIT 11053, Fundamentals of Programming

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

If Control Construct

CS1 Lecture 3 Jan. 18, 2019

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

Oct Decision Structures cont d

Chapter 3. Selections

CS302: Self Check Quiz 2

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

Variables and data types

CHAPTER 9 FLOW OF CONTROL

Selections. CSE 114, Computer Science 1 Stony Brook University

Built-in data types. logical AND logical OR logical NOT &&! public static void main(string [] args)

The following expression causes a divide by zero error:

CS 170 Section 3, Spring 2015 Programming in Java Midterm Exam 1. Name (print):

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

QUIZ: What value is stored in a after this

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

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

DECISION CONTROL AND LOOPING STATEMENTS

AP CS Unit 3: Control Structures Notes

Built-in data types. public static void main(string [] args) logical AND logical OR logical NOT &&! Fundamentals of Computer Science

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

MODULE 02: BASIC COMPUTATION IN JAVA

Introduc)on to C++ CS 16: Solving Problems with Computers I Lecture #2

CSE 8A Lecture 12. Reading for next class: : Sounds! Today s topics: Logical Operators:! && Start PSA 6: Chromakey!

Transcription:

if Statement Flow of Control: Branching (Savitch, Chapter 3) TOPICS Conditional Execution if,, and if boolean data switch statements CS 160, Fall Semester 2015 1 Programs o-en contain statements that may or may not be executed depending on condi7ons. An if statement checks whether a condi7on is true before deciding whether to execute some code. Condi7ons typically involve comparison of variables or quan77es for equality or inequality. if (age >= 18) Expression in parenthesis must evaluate to either true or false System.out.println( You are eligible to vote. ); CS 160, Fall Semester 2015 2 The if Statement The if statement has the following syntax if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped. Numeric Rela7onal Operators Math Java description < < Less than > > Greater than <= Less than or equal to >= Greater than or equal to = == Equal to!= Not equal to CS 160, Fall Semester 2015 3 CS 160, Fall Semester 2015 4 1

if Statement with An if statement may have an op7onal clause that will only be executed when the condi7on is false if ( wages <= 57600.0 ) tax = 0.124 * wages; tax = 0.124 * 57600.0; Give an example of when BOTH statements will execute? Give an example of when NEITHER statement will execute? NONE! One or the other must execute CS 160, Fall Semester 2015 5 Defining Blocks To execute more than one statement condi7onally, use to define a block (aka compound statement ) for the sequence of statements if (firstnumber <= secondnumber) quotient = secondnumber / firstnumber; remainder = secondnumber % firstnumber; quotient = firstnumber / secondnumber; remainder = firstnumber % secondnumber; CS 160, Fall Semester 2015 6 Cascading if- Statements if (condition1) if (condition2) statement3; Code wrinen: if (condition1) if (condition2) Dangling Be sure to use indentation properly Otherwise too difficult to read! Which if does the finish? will match to the nearest unmatched if within the same block CS 160, Fall Semester 2015 7 CS 160, Fall Semester 2015 8 2

Fix dangling using blocks Code wrinen: if (condition1) if (condition2) boolean Data Type boolean A primi7ve data type that can be set to: true false boolean correct = true; Notice there are no quotation marks around true and false! CS 160, Fall Semester 2015 9 CS 160, Fall Semester 2015 10 Boolean Expressions Condi7ons are expressions that have a truth value. Arithme7c rela7onal operators produce a truth value, e.g., 10 < 3 x > y a >= (b + 12) boolean Operators Logical and (conjunc7on) Java symbol && Math symbol true only when both expressions are true (MINIMUM_WAGE <= wages) && (wages <= MAXIMUM_WAGE) Logical inclusive or (disjunc7on) Java symbol Math symbol true when either or both expressions are true (wages < MINIMUM_WAGE ) (wages > MAXIMUM_WAGE ) CS 160, Fall Semester 2015 11 CS 160, Fall Semester 2015 12 3

boolean Operators (cont.) Logical exclusive or Java symbol ^ Math symbol true when exactly one of the expressions is true (MINIMUM_WAGE < wages) ^ (MINIMUM_WAGE == wages) Logical not (nega7on) Java symbol! Math symbol!(minimum_wage == wages) Java Logical and Arithme7c Operator Precedence Rules 1.! - (unary) 2. * / % 3. + - 4. < <= > >= 5. ==!= 6. ^ & 7. && 8. CS 160, Fall Semester 2015 13 CS 160, Fall Semester 2015 14 Complicated Boolean Expressions boolean isleapyear = ((year % 4) == 0) && ((year % 100)!= 0) ((year % 400) == 0); Interpreta7on: Leap years are every four years (divisible by 4) except for centuries that are not divisible by 400. Combining Rela7onal Operators Unlike some other operators, rela7onals cannot be combined in Java. (a <= b <= c) Does not mean a <= b and b <= c. It produces a compile- 7me error - - cannot compare a boolean (return value of <= operator) with a number. How should this be done? ( a <= b && b <= c) CS 160, Fall Semester 2015 15 CS 160, Fall Semester 2015 16 4

switch Statement Used to accomplish mul7- way branching based on the value of an integer, character, or string selector variable. switch (numberofpassengers) case 0: System.out.println( The Harley ); case 1: System.out.println( The Dune Buggy ); default: System.out.println( The Humvee ); Don t need a break after default already at end Expression in ( ) must be int, char, or String ONLY! break moves flow of control to end of switch statement default case is executed if no other case values match expression CS 160, Fall Semester 2015 17 Using break in switch statements Consider the code fragment below int i = 1; switch (i) case 0: System.out.println( 0 ); case 1: System.out.println( 1 ); case 2: System.out.println( 2 ); case 3: System.out.println( 3 ); System.out.println( ); Without breaks what is the output? (note: it is legal to leave out the breaks and some6mes desired) 1 2 3 CS 160, Fall Semester 2015 18 Why execute mul7ple cases? Consider if you want a base level with add- ons for increasing numbers as in switch (zoomember_level) case 500: System.out.print( Meet a tiger ); case 100: System.out.print( Free t-shirt ); case 50: System.out.print( Free admission! ); default: System.out.println(); Example of when we want to leave off the break statements to allow execu7on to follow through CS 160, Fall Semester 2015 19 Symbolic Constants in switch Statements final int SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; int d;... switch (d) case SUNDAY: System.out.print( Sunday ); case MONDAY: System.out.print( Monday ); case TUESDAY: System.out.print( Tuesday ); case WEDNESDAY: System.out.print( Wednesday ); case THURSDAY: System.out.print( Thursday ); case FRIDAY: System.out.print( Friday ); case SATURDAY: System.out.print( Ski day ); CS 160, Fall Semester 2015 20 5

Mul7ple case Labels switch example switch (d) case MONDAY: case WEDNESDAY: case FRIDAY: System.out.println( C.S. meets at 9:00 today ); System.out.println( Math meets at 10:00 today ); case TUESDAY: case THURSDAY: System.out.println( English meets at 9:00 today ); System.out.println( Chemistry meets at 10:00 today ); case SUNDAY: case SATURDAY: System.out.println( Enjoy the weekend ); CS 160, Fall Semester 2015 21 Display the students grade based on entering their grade as an int between 0 and 100 (90+ = A, 80-89 = B, 70-79 = C) switch( grade / 10 ) Integer division case 10: is our friend! case 9: System.out.println( A ); case 8: System.out.println( B ); case 7: System.out.println( C ); default: System.out.println( F ); CS 160, Fall Semester 2015 22 Comparing switch and if statements Comparing switch and if statements Print out whether the char ch is a vowel or not switch statement if equivalent switch statement if equivalent switch (expression) case value1: case value2: case valuex: statementx; default: statementy; value = expression; if (value == value1) if (value == value2) if (value == valuex) statementx; statementy; switch (letter) case A : case a : case E : case e : case I : case i : case O : case o : case U : case u : System.out.println( vowel ); default: System.out.println( consonant ); if ( letter == A letter == a letter == E letter == e letter == I letter == i letter == O letter == o letter == U letter == u ) System.out.println( vowel ); System.out.println( consonant ); CS 160, Fall Semester 2015 23 CS 160, Fall Semester 2015 24 6

Summary Flow of control if statements boolean expressions if- statements Order of opera7ons Rela7onal operators switch statement CS 160, Fall Semester 2015 25 7