CS 152 Computer Programming Fundamentals The if-else Statement

Similar documents
Introduction to Computer Science Unit 2. Exercises

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Java Basic Programming Constructs

AP CS Unit 3: Control Structures Notes

Chapter 3. Selections

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

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

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Spring University of New Mexico CS152 Midterm Exam. Print Your Name

Building Java Programs

CS 231 Data Structures and Algorithms, Fall 2016

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

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

Selected Questions from by Nageshwara Rao

Operators Questions

1.Which four options describe the correct default values for array elements of the types indicated?

Building Java Programs

CIS October 16, 2018

Chapter 4: Control Structures I

CS111: PROGRAMMING LANGUAGE II

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

CS Week 5. Jim Williams, PhD

JAVA OPERATORS GENERAL

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

H212 Introduction to Software Systems Honors

CS1150 Principles of Computer Science Boolean, Selection Statements

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

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

CS 11 java track: lecture 1

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

Question: Total Points: Score:

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

Question: Total Points: Score:

Full file at

AP CS Unit 8: Inheritance Exercises

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

CIS October 19, 2017

CIS March 1, 2018

Introduction to Java

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

Section 2.2 Your First Program in Java: Printing a Line of Text

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

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

AP COMPUTER SCIENCE A

Building Java Programs Chapter 2

Flow of Control. Chapter 3

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

Building Java Programs

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

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Flow of Control. Chapter 3

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

CSc 2010 Principles of Computer Science, Fall 2013 Practice Problems for Midterm 3* * 3 17 % 9-20 % (26 / 7) "2"

Place your name tag here

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

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

Assignment 2.4: Loops

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

CSE 1223: Exam II Autumn 2016

Prof. Navrati Saxena TA: Rochak Sachan

Oct Decision Structures cont d

4 Programming Fundamentals. Introduction to Programming 1 1

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

int x = 42, y = 33; //1 int z = x + y; //2 System.out.println(x + "+" + y + "=" + z); //3

Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination

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

Building Java Programs Chapter 2

Some Practice Midterm Problems

Chapter 3: Operators, Expressions and Type Conversion

AP CS Unit 6: Inheritance Exercises

CSIS 10A Assignment 4 SOLUTIONS

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

CS302: Self Check Quiz 2

CSE 142, Summer 2013 Midterm Exam, Friday, July 26, 2013

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Java Programming for Selenium

STUDENT LESSON A12 Iterations

CONDITIONAL EXECUTION

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

CSE 114 Computer Science I

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD

Exam Percentage: / 55 = %

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

CS111: PROGRAMMING LANGUAGE II

CIS 110 Introduction to Computer Programming Spring 2016 Midterm

Question: Total Points: Score:

CS 177 Spring 2010 Exam I

Programming Basics. Digital Urban Visualization. People as Flows. ia

CPSC 219 Extra review and solutions

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

Java Coding 3. Over & over again!

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CS 101 Exam 2 Spring Id Name

( &% class MyClass { }

1 Short Answer (10 Points Each)

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Transcription:

CS 152 Computer Programming Fundamentals The if-else Statement Instructor: Joel Castellanos e-mail: joel@unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building (ECE). Room 233 8/31/2017 a) b) c) 2 public class Tmp { public static void main(string[] args) { System.out.println("Pick Me"); } } public class Tmp { public static void main(string[] args) { System.out.println("No, Me"); } } public class Tmp { public static void main(string[] args) { System.out.println("Ooh, Ooh"); } } Quiz: Which is the Correct Formatting in CS-152? 1

Java Primitive Type: boolean public class Toy_3_2 { public static void main(string[] args) { boolean a = true; boolean b = (5*(-5)) > 0; 3 } } System.out.println(a); System.out.println(b); Output: true Logical Expressions 4 1. public class Hello 2. { public static void main(string[] args) 3. { 4. int a = 1; int b = 3; 5. System.out.println( a+b + 14 ); 6. System.out.println( a+b < 14 ); 7. System.out.println( a+b > 14 ); 8. System.out.println( a+b <= a*b ); 9. System.out.println( a+b > a*b ); 10. } 11. } Output: 18 true true 2

Logical Expressions 5 1. public class Hello 2. { public static void main(string[] args) 3. { 4. int a = 3; 5. int b = 5; 6. int c = 7; 7. System.out.println( c > a && c > b ); 8. System.out.println( b > a && b > c ); 9. System.out.println( b > c && b > a ); 10. System.out.println( b > a b > c ); 11. } 12. } Output: true true Using a boolean Variable to hold Results 6 1) public class Hello 2) { public static void main(string[] args) 3) { 4) int a = -3; 5) int b = 9; 6) int c = 5; Output: true 7) System.out.println((a+b>c) && (a*b>c)); 8) 9) boolean r1 = a+b > c; //true 10) boolean r2 = a*b > c; // 11) System.out.println( r1 && r2 ); 12) System.out.println( r1 r2 ); 13) } 14)} 3

Quiz: Logical Expressions What is the output of the println statement? int a = 3; int b = 5; int c = 7; System.out.println( (b < a && b < c) + " " + (b < a b < c) + " " + (b > c a > c) ); 7 a) true b) true c) true d) true true e) true true Quiz: Logical Expressions 8 What is the output of the println statement? int a = 3; int b = 5; int c = 11; System.out.println( (a+b > c && a*b > c) + " " + (a+b > c a*b > c) + " " + (a+b < c a*b < c)); a) true b) true c) true d) true true e) true true 4

The if Statement The if statement tells your program to execute a certain section of code only if a particular test evaluates to true. if (grade >= 90) System.out.println("Cash Award"); Logical expression One statement or one block { }. Executed only if logical expression is true 9 When the then part is more than one statement, brackets are needed. if (grade >= 90) { System.out.println("Cash Award"); cash = cash + 100.0; } if-else Statement Flow Chart 1) if (balance >= 0) 2) { balance = balance + (INTEREST * balance)/12; 3) } 4) else 5) { balance = balance - OVERDRAWN_PENALTY; 6) } Start true balance >= 0 10 balance = balance + (INTEREST * balance)/12; balance = balance - OVERDRAWN_PENALTY; 5

Quiz: Identifiers in All Caps public class BankBalance { public static final double OVERDRAWN_PENALTY = 8.00; public static final double INTEREST_RATE = 0.02; 11 public static void main(string[] args) { In the code segment from listing 3.1 shown above, OVERDRAWN_PENALTY and INTEREST_RATE in are in all caps: a) because they are outside main, and, therefore the code would not actually compile. b) because they are declared static. c) because they are declared final. d) because they are global class variables. e) because later they are used in different branches of an if. if and else Statements 12 1) public class Toy_3_1 2) { 3) public static void main(string[] args) 4) { 5) int x = 5; 6) 7) 8) Logical "is equal to" Operator if (x == (2+3)) x = x + 10; 9) else x = x * 2; 10) 11) 12) Assignment Operator System.out.println(x); 13) } 14)} Output: 15 6

if and else Statements 13 Either statement 2 or statement 5 will execute. It is impossible for both to execute. 1) if (testscore >= 90) 2) { System.out.println("Great Job!"); 3) } 4) else 5) { System.out.println("Work Harder"); 6) } Since the then part is only one statement, curly brackets are not needed. However, when the code does not fit on a single line, the CS-259 coding standard dictates that the curly brackets be used. if, else if, else 14 1) public class HelloWorld 2) { public static void main(string[] args) 3) { 4) int x = 1; 5) 6) if (x == 1) No semicolon!!! 7) { System.out.println("x is 1"); 8) } 9) else if (x == 2) No semicolon!!! 10) { System.out.println("x is 2"); 11) } 12) else No semicolon!!! 13) { System.out.println("x is special"); 14) } 15) } 16)} 7

Use of else if 15 1) public class HelloWorld 2) { public static void main(string[] args) 3) { int testscore = 76; 4) char grade = 'F'; 5) 6) if (testscore >= 90) grade = 'A'; 7) else if (testscore >= 80) grade = 'B'; 8) else if (testscore >= 70) grade = 'C'; 9) else if (testscore >= 60) grade = 'D'; 10) 11) System.out.println("Grade = " + grade); 12) } 13)} With testscore = 76, the logical expressions in lines 8 and 9 would both evaluate to true. However, since 8 is true, execution never reaches 9. Find the Syntax Error 1) public class HelloWorld 2) { public static void main(string[] args) 3) { int testscore = 76; 4) char grade; 5) 6) if (testscore >= 90) grade = 'A'; 7) else if (testscore >= 80) grade = 'B'; 8) else if (testscore >= 70) grade = 'C'; 9) else if (testscore >= 60) grade = 'D'; 10) 11) System.out.println("Grade = " + grade); 12) } 13)} Local variable grade may not have been initialized. 16 8

else: Ensuring grade is Initialized 17 1) public class HelloWorld 2) { public static void main(string[] args) 3) { int testscore = 76; 4) char grade; 5) 6) if (testscore >= 90) grade = 'A'; 7) else if (testscore >= 80) grade = 'B'; 8) else if (testscore >= 70) grade = 'C'; 9) else if (testscore >= 60) grade = 'D'; 10) else grade = 'F'; 11) System.out.println("Grade = " + grade); 12) } 13)} The compiler recognizes there is no path to line 11 in which grade is not initialized. Quiz: if and else if 1) int testscore = 88; 2) char grade = 'F'; 3) 4) if (testscore >= 60) grade = 'D'; 5) else if (testscore >= 70) grade = 'C'; 6) else if (testscore >= 80) grade = 'B'; 7) else if (testscore >= 90) grade = 'A'; 8) 9) System.out.println(grade); What would be the output of the above Java code? a) B b) D c) F d) FB e) FDCB 18 9

Control Flow and Program State 19 1) public class HelloWorld 2) { public static void main(string[] args) 3) { int x = 5; 4) int a = 0; 5) if (x < 10) a=1; 6) if (x < 6) a=2; 7) if (x < 1) a=3; 8) System.out.println(a); 9) } 10)} Table of program state at the start of each line in the order of execution. start x a of line line 3 line 4 5 line 5 5 0 line 6 5 1 line 7 5 2 line 8 5 2 Output: 2 Control Flow and Program State 20 1) public static void main(string[] args) 2) { int x = 5; 3) int a = 0; start x a of line 4) if (x < 10) line 2 5) { a=1; 6) } line 3 5 7) if (x < 6) line 4 5 0 8) { a=2; line 5 5 0 9) } line 7 5 1 10) if (x < 1) line 8 5 1 11) { a=3; line 10 5 2 12) } line 13 5 2 13) System.out.println(a); 14)} Output: 2 10

Control Flow: if & else if 21 1) public static void main(string[] args) 2) { int x = 5; 3) int a = 0; 4) if (x < 10) 5) { a=1; 6) } 7) else if (x < 6) 8) { a=2; 9) } 10) else if (x < 1) 11) { a=3; 12) } 13) System.out.println(a); 14)} start x a of line 2) 3) 5 4) 5 0 5) 5 0 13) 5 1 Output: 1 Quiz: if, else if, else 1) public static void main(string[] args) 2) { 3) int x = 1; 4) 5) if (x == 1) 6) { System.out.println("x is 1"); Look carefully 7) } This code does 8) else if (x == 2) not do what it was 9) { System.out.println("x is 2"); probably intended 10) } to do. 11) else x = 3; 12) { System.out.println("wild: x=" + x); 13) } 14) } 22 The output is: a) x is 1 b) x is 1 c) x is 2 d) wild: x=1 e) wild: x=3 wild: x=1 11

if, else if, else 23 1) public static void main(string[] args) 2) { 3) int x = 4; 4) 5) if (x == 1) 6) { System.out.println("x is 1"); 7) } 8) else if (x == 2) 9) { System.out.println("x is 2"); 10) } 11) else x = 3; 12) { System.out.println("x is " + x); 13) } 14) } Output: Only Change x is 3 Example: if, else if, else 24 1) int x=3, y=7; 2) if (x*x < x+y) 3) { System.out.print("B"); 4) } 5) if (x > 0) 6) { System.out.print("E"); 7) } 8) else if (y > 0) 9) { System.out.print("A"); 10) } 11) else 12) { System.out.print("T"); 13) } 14) if (x*y > 0) 15) { System.out.print("S"); 16) } Output: BES 12

Quiz: if & else if 1) public static void main(string[] args) 2) { 3) int x = 50; 4) if (x > 20) 5) { System.out.print("A"); 6) } 7) else if (x > 30) 8) { System.out.print("B"); 9) } 10) else if (x > 40) 11) { System.out.print("C"); 12) } 13) System.out.println("D"); 14) } 25 The output is: a) ABCD b) ABD c) CD d) C e) AD Quiz: if, else if 1) int a = 3, b = 4, c = 5; 2) 3) if (a+b > c) System.out.print("A"); 4) 5) else if (a*b > c) System.out.print("B"); 6) 7) if (a*a > c) System.out.print("C"); 8) 9) else if (b*b > c) System.out.print("D"); 10) 11) else if (b*b >= c*a) System.out.print("E"); 12) 13) System.out.println("F"); 26 The output of this Java code segment is: a) AF b) ACF c) ABCF d) ACDF e) ACDEF 13

Logical Operators 27 == Equals!= Not Equal < Less than > Grater than <= Less than or Equal to >= Greater than or Equal to Logical OR The bitwise operators are not covered in CS-259. && Logical AND bitwise OR! Logical NOT & bitwise AND ^ bitwise exclusive OR ~ bitwise NOT Truth Tables for AND, OR and NOT 28 1) public class TruthTables 2) { 3) public static void main(string[] args) 4) { 5) System.out.println( true && true ); 6) System.out.println( true && ); 7) System.out.println( && true); 8) System.out.println( && ); 9) 10) System.out.println( true true ); 11) System.out.println( true ); 12) System.out.println( true ); 13) System.out.println( ); 14) 15) System.out.println(!true); 16) System.out.println(!); 17) } 18)} true true true true true 14

The Logical AND Operator: && true when both parts are true 1) if ((pressure >= min) && (pressure <= max)) 2) { System.out.println("Pressure is OK"); 3) } 4) else 5) { System.out.println( 6) "Warning: Pressure is out of range."); 7) } 29 The order of operations, in Java, makes these equivalent: if ((pressure >= min) && (pressure <= max)) if ( pressure >= min && pressure <= max ) The Logical AND Operator: true when both parts are true true when either part is true 1) if ((pressure < min ) (pressure > max )) 2) { System.out.println( 3) "Warning: Pressure is out of range."); 4) } 5) else 6) { System.out.println("Pressure is OK"); 7) } 30 15

What Happens on Line 4? 31 1) public class TruthTable 2) { public static void main(string[] args) 3) { 4) System.out.println(xor(true, true)); 5) System.out.println(xor(true, )); 6) System.out.println(xor(, true)); 7) System.out.println(xor(, )); 8) } 9) 10) public static boolean xor(boolean a, boolean b) 11) { 12) return ( a b) &&!(a && b); 13) } 14) } ( T T) &&!(T && T) ( T ) &&!( T ) T && F F Truth Table for Exclusive OR T T = F T F = T F T = T F F = F Trace of What Happens on Line 5 32 1) public class TruthTable 2) { public static void main(string[] args) 3) { 4) System.out.println(xor(true, true)); 5) System.out.println(xor(true, )); true 6) System.out.println(xor(, true)); 7) System.out.println(xor(, )); 8) } 9) 10) public static boolean xor(boolean a, boolean b) 11) { 12) return ( a b) &&!(a && b); 13) } 14) } ( T F) &&!(T && F) ( T ) &&!( F ) T && T T Truth Table for Exclusive OR T T = F T F = T F T = T F F = F 16

33 Which of the if statements have identical truth tables? 1) public class TruthTable 2) { public static void main(string[] args) 3) { 4) foo(true,true); 5) foo(true,); 6) foo(,true); 7) foo(,); 8) } 9) CAT DOG CAT BAT DOG CAT BAT DOG ANT BAT 10) public static void foo(boolean a, boolean b) 11) { 12) if ( a b) System.out.print("CAT "); 13) if (!a &&!b) System.out.print("ANT "); 14) if (!( a && b)) System.out.print("BAT "); 15) if (!(!a &&!b)) System.out.print("DOG "); 16) System.out.println(); 17) } 18)} Short circuit Evaluation What is meant by this expression is safe. if (x!= 0.0 && 1.0/x > x + y) exp1 exp2 The expression: (exp1 && exp2) can only be true if both exp1 and exp2 are true. Thus, if exp1 is, Java does not evaluate exp2. Thus, if x = 0, then 1.0/x is not evaluated. 34 17

Order of Evaluation double x = 2.0; double y = -2.0; if (x!= 0.0 && 1.0/x > x + y) 1) x!= 0.0 2) 1.0/x 3) x + y 4) 0.5 > 0.0 5) true && true 35 6) true Comparing Strings 1) String mycolor = "red" 2) System.out.println(myColor); 3) System.out.println(myColor == "red"); 4) System.out.println(myColor.equals("red")); 36? 18

Comparing Addresses verses Strings String mycolor; //Some code that puts data in mycolor. mycolor == "red" true if and only if the memory location of mycolor is the same as the memory location of "red" mycolor.equals("red") true if and only if the data in mycolor is "red". 37 Possible Null Pointer Exception 1) String str = JOptionPane.showInputDialog(null, 2) "Enter red"); 3) if (str.equals("")) 4) { System.out.println("Clicked OK with no data"); 5) } 6) if (str == null) 7) { System.out.println("Clicked Cancel"); 8) } A Null Pointer Exception occurs when code attempts to access a member of an object using an object reference that is not pointing anywhere. In line 3, equals is a method that is a member of a String object. 38 However, if str is null, then, even though str was declared as being a reference to a String object, it doesn't, in fact, point to anything. 19

Does This Fix the Problem? 1) String str = JOptionPane.showInputDialog(null, 2) "Enter red"); 3) if (str == null) 4) { System.out.println("Clicked Cancel"); 5) } 6) if (str.equals("")) 7) { System.out.println("Clicked OK with no data"); 8) } 39 Checking Input: All Golden 1) String str = JOptionPane.showInputDialog( 2) null, "Enter red"); 3) if (str == null) 4) { System.out.println("Clicked Cancel"); 5) } 6) else if (str.equals("")) 7) { System.out.println("OK with no data"); 8) } 40 1) String str = JOptionPane.showInputDialog( 2) null, "Enter red"); 3) if (str == null) 4) { System.out.println("Clicked Cancel"); 5) System.exit(0); 6) } 7) if (str.equals("")) 8) { System.out.println("OK with no data"); 9) } 20

How can this be coded in Java? Let X be a course with 3 grades: a midterm, a final exam and a final project. Each counts as 1/3 of the course grade. Example: t 1 =90, t 2 =70, p=80 grade = 80.0 However, if a student does better on the final than on the midterm, then the final is counted with twice the weight as the midterm. Example: t 1 =0, t 2 =90, p=90 grade = 70.0 A student who gets a 95% or more on the final project can drop his or her final exam score and count the final project as 2/3 and the midterm as 1/3 of the course grade. Example: t 1 =90, t 2 =0, p=90 grade = 90.0 41 Example Calculation: Count Final 2x Midterm Case 1 Paper & Pencil before code! grade = (t 1 + t 2 + p)/3 Given: grade = (w)t 1 + (2w)t 2 + (1/3)p w + 2w + 1/3 = 1 42 Case 2 Counting t 2 with twice the weight as t 1 w + 2w = 2/3 3w = 2/3 w = 2/9 grade = (2/9)t 1 + (4/9)t 2 + (1/3)p 21

Java Code for Conditional Grade 43 1) Scanner in = new Scanner(System.in); 2) double t1 = in.nextdouble(); Could or 3) double t2 = in.nextdouble(); Should the 4) double p = in.nextdouble(); order of the 5) two if 6) double grade = (t1 + t2 + p) / 3.0; statements 7) be switched? 8) if (t2 > t1) 9) { grade = t1*(2.0/9.0) + t2*(4.0/9.0) + p/3.0; 10) } 11) Could or Should this be changed to else if? 12) if (p >= 95) 13) { double tmp = (t1/3.0) + (p*2.0/3.0); 14) if ( tmp > grade) grade = tmp; 15) } 16) System.out.println("Grade="+grade); 22