CONDITIONAL EXECUTION

Similar documents
CONDITIONAL EXECUTION

Variables and data types

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

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

Selections. CSE 114, Computer Science 1 Stony Brook University

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

Conditionals, Loops, and Style

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

Chapter 3 Selection Statements

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

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

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Lecture 1 Java SE Programming

Chapter 3. Selections

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

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

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

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

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

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

DATA TYPES AND EXPRESSIONS

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

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

CS1150 Principles of Computer Science Loops (Part II)

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Repetition, Looping. While Loop

1.3 Conditionals and Loops

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

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Condi(onals and Loops

CS 112 Introduction to Programming

3chapter C ONTROL S TATEMENTS. Objectives

Eng. Mohammed S. Abdualal

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

MODULE 02: BASIC COMPUTATION IN JAVA

1.1 Your First Program

1.3 Conditionals and Loops

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

Scope of this lecture. Repetition For loops While loops

3. Conditionals & Loops

3. Conditionals and loops

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

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

PROGRAMMING STYLE. Fundamentals of Computer Science I

1.3 Conditionals and Loops

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

1.1 Your First Program

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

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Chapter 4: Control Structures I

1.1 Your First Program

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

AP CS Unit 3: Control Structures Notes

Zheng-Liang Lu Java Programming 45 / 79

JAVA OPERATORS GENERAL

Advanced if/else & Cumulative Sum

3. Conditionals & Loops

( &% class MyClass { }

Building Java Programs

Selection Statements. Pseudocode

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

CMPT 125: Lecture 4 Conditionals and Loops

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

Chapter 2 Primitive Data Types and Operations. Objectives

1.1 Your First Program

Computational Expression

Topics. Chapter 5. Equality Operators

CSCI 135 Midterm Fundamentals of Computer Science I Fall 2011

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Lecture 2: Intro to Java

Elementary Programming

1.1 Your First Program

Java Simple Data Types

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Important Java terminology

Loops. GEEN163 Introduction to Computer Programming

Introduction to Computer Science Unit 2. Notes

Building Java Programs

1.3 Conditionals and Loops

Final Examination Semester 2 / Year 2011

Course Outline. Introduction to java

Computer Programming, I. Laboratory Manual. Final Exam Solution

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

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

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

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

PROGRAMMING FUNDAMENTALS

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

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

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

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

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

AP COMPUTER SCIENCE A

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Controls Structure for Repetition

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

1. Find the output of following java program. class MainClass { public static void main (String arg[])

Oct Decision Structures cont d

Transcription:

CONDITIONAL EXECUTION yes x > y? no max = x; max = y; logical AND logical OR logical NOT &&! Fundamentals of Computer Science I

Outline Conditional Execution if then if then Nested if then statements

Comparisons Given two numbers return a boolean operator meaning true example false example == equal 7 == 7 7 == 8!= not equal 7!= 8 7!= 7 < less than 7 < 8 8 < 7 <= less than or equal 7 <= 7 8 <= 7 > greater than 8 > 7 7 > 8 >= greater than or equal 8 >= 2 8 >= 10 Is the sum of a, b and c equal to 0? (a + b + c) == 0 Is grade in the B range? (grade >= 80.0) && (grade < 90.0) Is sumitems an even number? (sumitems % 2) == 0 3

Leap Year Example Years divisible by 4 but not by 100 leap year Years divisible by 400 leap year public class LeapYear { public static void main(string [] args) { int year = Integer.parseInt(args[0]); boolean isleapyear; // Leap year if divisible by 4 but not by 100 isleapyear = (year % 4 == 0) && (year % 100!= 0); // But also leap year if divisible by 400 isleapyear = isleapyear (year % 400 == 0); System.out.println(isLeapYear); % java LeapYear 2000 true 4

Control flow thus far public class ArgsExample { public static void main(string [] args) { time 0 String product = args[0]; 5 time 1 int qty = Integer.parseInt(args[1]); time 2 double cost = Double.parseDouble(args[2]); time 3 time 4 time 5 time 6 double total = qty * cost; System.out.print("To buy " + qty); System.out.print(" " + product); System.out.println(" you will need $" + total);

animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; 6 radius allocate memory for radius no value // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area);

animation Trace a Program Execution 7 public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); radius area memory no value no value allocate memory for area

animation Trace a Program Execution public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; 8 radius area assign 20 to radius 20 no value // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area);

animation Trace a Program Execution 9 public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20; // Compute area area = radius * radius * 3.14159; radius area memory 20 1256.636 compute area and assign it to variable area // Display results System.out.println("The area for the circle of radius " + radius + " is " + area);

animation Trace a Program Execution 10 public class ComputeArea { /** Main method */ public static void main(string[] args) { double radius; double area; // Assign a radius radius = 20; radius area memory 20 1256.636 // Compute area area = radius * radius * 3.14159; // Display results System.out.println("The area for the circle of radius " + radius + " is " + area); print a message to the console

Control flow Interesting and powerful programs need: To skip over some lines To repeat lines Conditionals sometimes skip parts Loops allow repetition of lines (we will talk about these in a future lecture

if Statement Most common branching statement Evaluate a boolean expression, inside the ()'s If true, do some stuff [optional] If false, do some other stuff Note lack of semicolon! if (expression) { statement1; statement2; Curly braces used to denote a code "block": All lines in block get executed (in sequence) or none of the them do if (expression) { statement1; statement2; { statement3; statement4;

13 One-way if Statements if (boolean-expression) { statement(s); if (radius >= 0) { area = radius * radius * PI; System.out.println("The area" + " for the circle of radius " + radius + " is " + area); Boolean Expression false (radius >= 0) false true true Statement(s) area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area); (A) (B)

Note 14 if i > 0 { System.out.println("i is positive"); (a) Wrong if (i > 0) { System.out.println("i is positive"); (b) Correct if (i > 0) { System.out.println("i is positive"); (a) Equivalent if (i > 0) System.out.println("i is positive"); (b)

The Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; { statement(s)-for-the-false-case; 15 true Statement(s) for the true case Boolean Expression false Statement(s) for the false case

16 if... Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the + circle of radius " + radius + " is " + area); { System.out.println("Negative input");

Multiple Alternative if Statements 17 if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F'; Equivalent if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F';

animation Trace if- statement 18 Suppose score is 70.0 The condition is false if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F';

animation Trace if- statement 19 Suppose score is 70.0 The condition is false if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F';

animation Trace if- statement 20 Suppose score is 70.0 The condition is true if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F';

animation Trace if- statement 21 Suppose score is 70.0 grade is C if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F';

animation Trace if- statement 22 Suppose score is 70.0 Exit the if statement if (score >= 90.0) grade = 'A'; if (score >= 80.0) grade = 'B'; if (score >= 70.0) grade = 'C'; if (score >= 60.0) grade = 'D'; grade = 'F';

Note The clause matches the most recent if clause in the same block. 23 int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); System.out.println("B"); (a) Equivalent int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); System.out.println("B"); (b)

Note, continued 24 Nothing is printed from the preceding statement. To force the clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); System.out.println("B"); This statement prints B.

Common Errors 25 Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); Wrong { area = radius*radius*pi; System.out.println("The area for the circle of radius " + radius + " is " + area); This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style.

26 TIP if (number % 2 == 0) even = true; even = false; (a) Equivalent boolean even = number % 2 == 0; (b) if (even == true) System.out.println( "It is even."); (a) Equivalent if (even) System.out.println( "It is even."); (b)

Truth Table for Operator ^ 27 p1 p2 p1 ^ p2 false false false false true true true false true true true false Example (assume age = 24, gender = 'F') (age > 34) ^ (gender == 'F') is true, because (age > 34) is false but (gender == 'F') is true. (age > 34) (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false.

Companion Website The & and Operators 28 You can use & and instead of && and Double operators provide lazy evaluation Single operators force evaluation of all clauses in the boolean expression

Companion Website The & and Operators 29 If x is 1, what is x after this expression? (x > 1) & (x++ < 10) If x is 1, what is x after this expression? (1 > x) && ( 1 > x++) How about (x is 1 to start): (1 == x) (10 > x++)? (1 == x) (10 > x++)?

if statement {'s optional if only one statement if (expression) statement1; Example: if (x > y) max = x; max = y; if (expression) statement1; statement2; yes x > y? no max = x; max = y;

if examples if (x < 0) x = -x; Take absolute value of x if (Math.random() < 0.5) System.out.println("heads"); System.out.println("tails"); Flip a fair coin and print out the results. if (x > y) { int t = x; x = y; y = t; Put x and y into sorted order num = 0; if (args.length > 0) { num = Integer.parseInt(args[0]); If a command line option is passed in, use it as the value for num.

32 Let s Try One!! If the unicorn is mythical, then it is immortal, but if it is not mythical, then it is a mortal mammal. If the unicorn is either immortal or a mammal, then it is horned. The unicorn is magical if it is horned. Write a program named unicorn.java that determines whether unicorns are mythical, immortal, mortal, mammal, magical or horned, and output these to the screen. You should only output those characteristics that are true. Notice, there is no user input to this program. Your program only needs to use the above statements to determine which characteristics are true.

Summary Conditional Execution if then if then Nested if then statements