comp-202: foundations of programmingcs202/2015-05/web/... · expressions • an expression is a...

60
COMP-202: Foundations of Programming Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Upload: others

Post on 24-Jun-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

COMP-202: Foundations of Programming

Lecture 3: Boolean, Mathematical Expressions, and Flow Control

Sandeep Manjanna, Summer 2015

Page 2: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Announcements

• Slides will be posted before the class. There might be few

minor changes later.

• Extra class on the 20th of May (13:05-15:25) at TR0100

• Assignment 1 extended due date.• New Due Date : 17th of May (@ 23:30)

• Try all the exercises on the class slides. See me during

office hours for any doubts and troubles solving them.

• Thanks for the responses on the survey.

Page 3: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Survey Results

Can be a bit faster

Good, slower is

better

Very helpful

Prefer more

details

Page 4: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Review

• Variables

• Data Types

• Strings

• User inputs

Page 5: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Reviewimport java.util.Scanner;

public class SimpleInterest

{

// A program to compute Simple Interest

public static void main(String[] args)

{

double principal, rateInterest;

int yrs;

Scanner inputReader = new Scanner(System.in);

System.out.println(“Enter the Principal Amount”);

principal = inputReader.nextDouble();

System.out.println(“Enter the Annual Rate of Interest”);

rateInterest = inputReader.nextDouble();

System.out.println(“Enter the number of years since loan”);

yrs = inputReader.nextInt();

double simpleInterest = (principal * rateInterest * yrs) / 100;

System.out.println(“Your simple interest after ” + yrs + “ years = ” + simpleInterest);

}

}

Page 6: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Data Types Review

• What data type and value do the following expressions evaluate to?

(int) 5.67 + (3 / 2)

(7 / 4) < (7.0 / 4.0)

25 + “Hello”

((int) 3.1 + 5) / 3.0

Page 7: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

This Lecture

� Boolean Expressions

� Mathematical Expressions

� Flow Control

One step at a time….

Page 8: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Expressions• An expression is a construct made up of variables, operators,

and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.

• An Expression has Operator acting on the Operands to generate a single valued result.

int x = 5 + 10;

String s = “Hello ” + “COMP202”;

• The data type of the result depends both on the operator and the operands.

• An Expression is always evaluated from left to right, unless it is explicitly specified.

• There are exceptions depending on the precedence of the operator. We will see operator precedence later in the class.

Page 9: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Boolean Expressions

Page 10: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Boolean Expressions

• Boolean expressions evaluate to either true or false.

myNumber > 0 // can be either true or false

• You can assign the result of a boolean expression to a variable of type boolean:

boolean positive;

positive = (myNumber > 0);

Page 11: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Boolean Expressions in Java

• A boolean expression is one of the following:

• Comparison of two values using a comparison operator like ‘<’. ( x < 5)

• true or false (Java's boolean literals – these are keywords).

• A variable which has type boolean. (boolean x;)

• The result of a logical operator over other boolean variables.

Page 12: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Comparison Operators

• The result of a comparison is always true or false. Used to compare numeric or character values (remember ASCII?)

== : equal to

!= : not equal to

< : less than

> : greater than

<= : less than or equal to

>= : greater than or equal to

Page 13: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Examples

int x = 5;

x < 6 true

x <= 5 true

x > 5 false

x >= 3 true

x == 5 true

x != 5 false

true

true

false

true

true

false

Page 14: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Careful!

• Terrible things will happen if you mistype == as =

int x = 5;

int y = 3;

(x = y);

x is overwritten with the value of y, i.e. x=3 after this

statement. This expression will return the value assigned to x, that will be int in this case not boolean (because, “=” is not a comparison operator).

(x = = y);

This sets check to false because x is not equal to y. This is

the right way to compare. This expression will return a boolean (true or false).

Page 15: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Logical Operators

• These take boolean expressions as input, and produce a result of type boolean.

! Logical NOT

|| Logical OR

&& Logical AND

• They can have either one operand (unary), as in NOT, or two operands (binary), as in OR and AND.

Page 16: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

! Operator

• The NOT operator flips the truth value of the boolean expression that follows.

• For an input boolean expression X:

X !X

true false

false true

Page 17: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

! Operator Examples

!(2 < 3)

!(3 < 2)

!true

!false

!(!(3>2))

!(September comes after August)

!(Earth is the 6th planet from the sun)

Page 18: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

&& Operator

• The AND operator is true if both of the input boolean expressions evaluate to true.

• For input boolean expressions X and Y:

X Y X&&Y

true true true

true false false

false true false

false false false

Page 19: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

&& Operator Examples

(1 < 2) && (2 < 3)

(1 < 1) && (2 < 3)

(!(1 < 1)) && (2 < 3)

(Television starts with a T) && (Java can also be coffee)

(true && false)

Page 20: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

|| Operator

• The OR operator is true if at least one of the input boolean expressions evaluate to true.

• For input boolean expressions X and Y:

X Y X||Y

true true true

true false true

false true true

false false false

Page 21: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

|| Operator Examples

(1 < 1) || (2 < 3)

!((3 < 4) || (100 > 1000))

((Vegetables are healthy) || (Fruit is healthy))

(true || false)

Page 22: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Short-Circuit Evaluation

• The evaluation of && and || stops as soon as you know the end result:

• If the left operand of && is false, the whole thing is false, so the second is never looked at.

(p1 && p2) – if p1 is false, p2 is never looked at.

• If the left operand of || is true, the whole thing is true, so the second is never looked at.

(p1 || p2) – if p1 is true, p2 is never looked at.

• This seems like a minor detail, but is important.

Page 23: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

How This Is Useful

• Use the first part to check to make sure the second part can actually be run

((x != 0) && ((1 / x) < 5))

• This can be used to check if the program is trying to divide by zero.

Page 24: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Example Question

• Which of the following best describes the set of all pairs of values

for boolean variables a and b, such that

(!a && b) == !(a || b)

evaluates to true?

a) Empty set

b) Only one pair: a == true, b == false

c) Two pairs in which a == true

d) Two pairs in which a != b

e) All four possible combinations of values

ANSWER: ( C )

Page 25: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Mathematical Expressions

Page 26: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Mathematical Operators

• Some operators:Addition (+)

Subtraction (-)

Multiplication (*)

Division (/)

Remainder (a.k.a., modulo) (%)

• How these operators actually function depends on the data type of the operands.

Page 27: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

+ Operator

As seen already,

int + int

3 + 4 � 7 (int)

int + double (or double + int)

3 + 4.0 � 7.0 (double)

• Also defined for:

String + String

"3" + "4" � "34" (String)

String + primitive data type (or p.d.t. + String)

3 + "4" � "34" (String)

Page 28: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

-, * Operators

• Subtraction (e.g., 3 - 4) and multiplication work as you would expect.

• Like for +, if you mix ints and doubles, you get a double.

• But not defined for as many data types• String * String � ERROR

Page 29: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Integer Division

• If both operands to the division operator are int, the result is also an int (with the fractional part discarded)

11 / 3 � 3

-11 / 3 � -3

• Division by 0 with integers causes a runtime error. Not detected at compile time!

1 / 0 � CRASH

Page 30: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

% Modulo Operators

• Modulo operator gives the remainder of a division.

• Example:5 % 3 � 2

4 % 2 � 0

1234 % 100 � 34

2

0

34

Page 31: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Operator Precedence

1. Parenthesis

2. Casting

3. *, /, % from left to right

4. +, -, from left to right

• Assignment happens after the evaluation of the expression.

• To reduce ambiguity and to make your life easy, always use parenthesis.

Page 32: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Operator Precedence

• Few Examples:

1.0 / 2

4 / 3 + 4.0 / 3

(double) 1 / 2

(double) (1 / 2)

( 1 + 2 ) * 3

1 + 2 * 3

You can learn more on operator precedence at: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Page 33: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

+=, ++ (shorthand operators)

• Programmers got lazy about writingx = x + 5;

• So, as a shortcut, you can write!!x += 5;

• Then they got even lazier about writingx += 1;

• So, as a short, you can writex++;

Page 34: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

-=, *=, /=, --

• Similarly:x -= 5; is the same as x = x - 5;

• And likewise for *=, /=.

• Also,x--; is the same as x -= 1;

or x = x - 1;

Page 35: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

++, --(Increment Operator)

• You can put ++ or -- before or after a variable name, and even as part of a complex expression.

• After (post increment) x++: use and then increment.

• Before (pre increment) ++x: increment and then use.

int x = 5, y = 5;

System.out.println(x++);

System.out.println(++y);

Page 36: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Recommendation

• Only use ++ or -- by themselves, and do not put them inside other expressions.

int x = 5;

int y = 2 * x++ + 4; // legal, but confusing

• Other shorthand operators are not very useful and are not seen in general programming practices.

Page 37: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Example Question

1) What is the output?

int i = 10;

int n = i++;

System.out.println(“Value i = ” + i + “ and n = ” + n);

2) What is the output?

int i = 10;

i++;

int n = i;

System.out.println(“Value i = ” + i + “ and n = ” + n);

Answer: Value i = 11 and n = 10

Answer: Value i = 11 and n = 11

Page 38: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Try it out

• Write a program that takes a 3-digit number and checks if the digits are in ascending order.

• For example: If the input is 321 , your program should output true.

If the input is 213, your program should output false.

• Hint: break it down into the following steps:1. Set up main method in a class

2. Get the Scanner working

3. Separate every digit of the number (as in unit place, ten’s place, hundred’ place)

4. Use Boolean expressions to generate the required result.

Page 39: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Conditionals(Testing)

..........

Page 40: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Control Flow

• Up to this point, our programs proceed in a "straight" fashion.

• Just follow each line of code in the main method

• There are commands that can decide if a particular block of code needs to be executed or not.

• These commands refer to the control flow because you control where the program execution goes next.

Page 41: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Control Flow

1. if statements

2. if-else statements

3. if-else if-else statements

4. while loops

5. for loops

Page 42: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

if and if-else

if (<condition>)

{

<body statements 1>

}

if (<condition>)

{

<body statements 1>

}

else

{

<body statements 2>

}

Page 43: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

( if ) and (if-else)

Page 44: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Example• Example: Print different things depending on what the

String we are given is.

Scanner scanner = new Scanner(System.in);

String languageChoice = scanner.nextLine();

if (languageChoice.equals("English"))

{

System.out.println("You chose English.");

}

else

{

System.out.println("You chose non-English.");

}

Page 45: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Structure of a Conditional

if (languageChoice.equals("English"))

{

System.out.println("You chose English.");

}

else

{

System.out.println("You chose non-English.");

}

The condition to check (make sure it is surrounded by parentheses)

Page 46: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Structure of a Conditional

if (languageChoice.equals("English"))

{

System.out.println("You chose English.");

}

else

{

System.out.println("You chose non-English.");

}

The block of code executes if the condition evaluates to true.

Page 47: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Structure of a Conditionalif (languageChoice.equals("English"))

{

System.out.println("You chose English.");

}

else

{

System.out.println("You chose non-English.");

}

The second block of code gets evaluated if the condition evaluates to false. If there is no else block, no extra code block is run.

Page 48: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

if-if vs. if-else

• What is the difference?

Both blocks on the left could execute, if at the end of the first block, (not condition) somehow becomes true.

if (condition) {

//some commands here

}

if (not condition) {

//more commands here

}

if (condition) {

//some commands here

}

else {

//more commands here

}

Page 49: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Going Into Two if Statements

int x = 1;

if (x > 0)

{

System.out.println("Positive. Altering the value.");

x--;

}

if (x <= 0) {

System.out.println("Not positive");

}

Page 50: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Only One Branch Executes

int x = 1;

if (x > 0)

{

System.out.println("Positive. Resetting value.");

x--;

}

else

{

System.out.println("Not positive");

}

Page 51: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

if - else if - else

• For when you have a more complicated set of conditions with more than two options.

• Option 1: Nested if-else statements

if (condition 1) { … }

else {

if (condition 2) { … }

else {

if (condition 3) { … }

}

}

Page 52: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Better Way (else if)

• Option 2: All at the same level

if (condition 1) {

}

else if (condition 2) {

}

else if (condition 3) {

}

else {

}

Page 53: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

if - else if - else

Page 54: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Order Matters

• Much like else, the "else if" is only entered if the prior conditions were false.

• So, there can be a big difference if the order of the options are changed.

Page 55: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

What Is Wrong Here?

if (money > 0.0) {

System.out.println("Positive balance");

}

else if (money > 1000.0) {

System.out.println("You're rich!");

}

else {

System.out.println("Uh-oh.");

}

What happens if the variable money = 1200?

Page 56: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Omitting Curly Braces

• A dangerous game.

if (x < 0)

System.out.println("x is less than zero.");

System.out.println("x is definitely negative.");

• Remember that Java ignores the indentation, so this is very misleading!

Page 57: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Example Question1) What will be the value of x after the following section of code executes:

int x = 5;

if (x > 3)

x = x – 2;

else

x = x + 2;A. 1 B. 3 C. 5 D. 7

2) What will be the value of b after the following section of code executes:

int a = 4, b = 0;

if (a < 3)

b = 4;

else if ( (a < 10) && (b>0) )

b = 3;

else if ( (a > 5) || (b==0) )

b = 2;

else

b = 1;A. 1 B. 0 C. 2 D. 4

Answer: B

Answer: C

Page 58: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Try it out!!

• Extend your previous program to convert temperatures.

1. Now, it first asks if the user wants to convert from Fahrenheit to Celsius.

2. If the user replies "true", it works as before.

3. Otherwise, it converts from Celsius to Fahrenheit.

Page 59: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Try it out!!

• Read three positive integers x, y, and z from the user and report the maximum and the minimum integers.

Page 60: COMP-202: Foundations of Programmingcs202/2015-05/web/... · Expressions • An expression is a construct made up of variables, operators, and method invocations, which are constructed

Summary

� Boolean Expressions

� Mathematical Expressions

� Conditional Statements

� if

� if – else

� if – else if