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

Post on 24-Jun-2020

4 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

COMP-202: Foundations of Programming

Lecture 3: Boolean, Mathematical Expressions, and Flow Control

Sandeep Manjanna, Summer 2015

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.

Survey Results

Can be a bit faster

Good, slower is

better

Very helpful

Prefer more

details

Review

• Variables

• Data Types

• Strings

• User inputs

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);

}

}

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

This Lecture

� Boolean Expressions

� Mathematical Expressions

� Flow Control

One step at a time….

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.

Boolean Expressions

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);

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.

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

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

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).

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.

! 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

! Operator Examples

!(2 < 3)

!(3 < 2)

!true

!false

!(!(3>2))

!(September comes after August)

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

&& 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

&& 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)

|| 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

|| Operator Examples

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

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

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

(true || false)

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.

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.

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 )

Mathematical Expressions

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.

+ 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)

-, * 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

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

% Modulo Operators

• Modulo operator gives the remainder of a division.

• Example:5 % 3 � 2

4 % 2 � 0

1234 % 100 � 34

2

0

34

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.

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

+=, ++ (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++;

-=, *=, /=, --

• 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;

++, --(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);

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.

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

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.

Conditionals(Testing)

..........

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.

Control Flow

1. if statements

2. if-else statements

3. if-else if-else statements

4. while loops

5. for loops

if and if-else

if (<condition>)

{

<body statements 1>

}

if (<condition>)

{

<body statements 1>

}

else

{

<body statements 2>

}

( if ) and (if-else)

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.");

}

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)

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.

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.

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

}

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");

}

Only One Branch Executes

int x = 1;

if (x > 0)

{

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

x--;

}

else

{

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

}

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) { … }

}

}

Better Way (else if)

• Option 2: All at the same level

if (condition 1) {

}

else if (condition 2) {

}

else if (condition 3) {

}

else {

}

if - else if - else

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.

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?

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!

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

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.

Try it out!!

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

Summary

� Boolean Expressions

� Mathematical Expressions

� Conditional Statements

� if

� if – else

� if – else if

top related