COMPUTER
SCIENCE
CSI141
PROGRAMMING
h t t p : ht t p : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l
PRINCIPLES
Object Oriented Programming T ALLMAN NKGAU
B OOLEANS , SELECTION &
REPETITION
‣ Booleans
‣ Selection/Conditionals
http:http://horstmann.com/bjlo/index.html
Object Oriented Programming T ALLMAN NKGAU
A CKNOWLEDGEMENT :
S LIDES’ THEME FROM
R OBERT S EDGEWICK | K EVIN W AYNE
http:http://horstmann.com/bjlo/index.html
L EARNING OUTCOMES
At the end of the lecture, you should be able
to:
‣ Declare Boolean variables
‣ Draw memory model diagrams involving Boolean
variables
‣ Use Boolean variables to create more complex
Boolean expressions
‣ Use comparison operators to create Boolean
h t t p : ht t p : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l
expressions
‣ Use selection statements in programs to solve
computational problems
Pause…
Write a Java program to read a positive
integer from the keyboard and display
“Even” if the integer is odd, otherwise it
should display “Odd”.
B OOLEANS
‣ Booleans
‣ Selection/Conditionals
h t t p : ht t p : / / h o r s t m a n n . c o m / b j l o / i n d e x . ht m l
Boolean data type
❑ Useful in making logical decisions
A variable is a storage location
with a name
Type Size in bytes Set of values Operations
boolean 1 true, false && (and), || (or), !
(not)
boolean data type – declaration & assignment
Memory diagram
boolean isOk;
boolean isTheEnd; isOk true
isOk = true; isTheEnd false
isTheEnd = false;
a b a && b a || b
false false false false
false true false true Relational operators
true false false true Math Meaning Java Notation
true true true true Notation
= Equal to ==
a !a ≠ Not equal to !=
false true > Greater than >
≥ Greater than or equal >=
true false to
Operands must have the < Less than <
same type or be ≤ Less than or equal to <=
compatible
Examples
Example
// Declarations Memory diagram
int number = 1, i = 3; number 1
int counter = 0; i 3
boolean isPositive, isOk;
// Processing counter 0
isOk = counter >= number;
isPositive false
isPositive = counter > 0;
isOk = i != counter; isOk
false true true true false
isOk = ((number + 2) == i);
isOk = (−1 * counter+2) <= (number + i);
isOk = (′A′ == ′a′);
Exercises
Assume:
・ int i = 10, x=3;
・ boolean flag, isOdd, isOk;
Write Java statements to perform each of the
following:
1. Assign the value true to flag when i is positive
2. Assign the value true to isOk when i is negative
3. Assign the value true to isOk when i is equal to 0
4. Assign the value true to flag when i is even
5. Assign the value true to isOdd when i is odd
6. Assign the value true to isOk when i is a multiple
of x
Exercises
Assume:
・i, x and y have been declared as int variables, and
initialized to appropriate values
・ boolean flag, isOk;
Write Java statements to perform each of the following:
1. Assign the value true to flag when i is a multiple of both
x and y
2. Assign the value false to isOk when i is an odd number
and is divisible by y
Examples
❑Given integers a = 100 and b = 25, write a Java statement assigning
a boolean variable inRange the value true if the integer variable c is
between a and b.
❑A year is the beginning of a century if its divisible by 100. Write a
java statement assigning true to the variable bCentury if the value in
the integer variable year is a year that begins a century.
❑A leap year is a year that 1) is divisible by 400 OR 2) is divisible by
4 but not by 100. Write a Java program to read a year and display
true if it’s a leap year and false otherwise.
❑A quadratic, 𝒂𝒙 𝟐 + 𝒃𝒙 + 𝒄, has real solutions if its discriminant is
greater than or equal to 0. Write a Java program to read coefficients
a, b, and c, computes the discriminant and display true if its greater
than or equal to 0, false otherwise.
Example
Given a four digit year, is it a leap year?
- If it is divisible by 400 or divisible by 4 but not by 100.
import java.util.Scanner;
public class LeapYear
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int year = in.nextInt();
boolean isLeapYear = (year % 400 == 0) ||
((year % 4 == 0) && (year % 100 != 0));
System.out.printf(“Is %d a leap year? %s\n”, year,
String.valueOf(isLeapYear) );
}
}
Selection: if – else statement
if - else statement:
A statement which allows a program to choose an
action depending on the value of a boolean expression.
Example
if time is 7pm then watch BTV news else watch Channel O
if day is Monday attend CSI142 lecture else go to the library
Etc.
14
if – else statement (cont.)
if - else statement:
A statement which allows a program to choose an action
depending on the value of a boolean expression.
Syntax:
if (boolean_expression) // branching condition
Statement_1; // executed if boolean_expression
evaluates to true
else
Statement_2; // executed if boolean_expression
evaluates to false
The above represents a two-way branch
・ If a certain condition holds execute statement_1
・ else execute statement_2
15
Example boolean Expression
import java.util.Scanner;
…
Scanner scan = new Scanner (System.in);
String message;
int finalMark;
// input final score
if part finalMark = scan.nextInt();
// processing
if (finalMark >= 50) {
message = “Passed CSI141”;
}
else {
message = “Failed CSI141”;
}
// Output
System.out.printf(“%s\n”, message);
else part 16
if-else logic
finalMark = scan.nextInt();
true finalMark false
>= 50 ?
message = message =
“Passed CSI141” “Failed CSI141”
System.out.printf(“%s\n”, message);
17
if- else: Multiple Statements
At times there is a need to execute more than one statement
Multiple statements MUST be placed inside braces, { }
・E.g. Statement_block_1 is a block of code
Syntax
if (boolean_expression) {
Statement_block_1; Statement1
else …
Statement_block_2; Statementn
}
18
Example
import java.util.Scanner;
…
Scanner scan = new Scanner (System.in);
int minMark, yourMark;
boolean results;
// input
System.out.printf(“Enter test mark: ”);
yourMark = scan.nextInt();
// processing
minMark = 74;
results = (yourMark > minMark);
if (results) {
System.out.printf(“Congrats!!!”);
System.out.printf(“You qualify as a student TA\n”);
}
else {
System.out.printf(“Sorry.”);
System.out.printf(“You do not qualify\n”);
}
19
if- else: without the else part
• Used if we want to execute some statements
only when the condition is true.
• Same as having an empty else
statement/statement block
Syntax:
if (boolean_expression)
Statement;
OR
if (boolean_expression) {
Statement; We prefer this
}
20
Example
import java.util.Scanner;
Scanner scan = new Scanner (System.in);
int minMark, yourMark;
boolean results;
// input
System.out.printf(“Enter test mark ”);
yourMark = scan.nextInt();
// processing
minMark = 74;
results = (yourMark > minMark);
if (!results) {
System.out.printf(“You don’t stand a chance!”);
}
No else
part 21
Pause…
Flipping a coin
import java.util.Random;
public class Flip
public static void main(String[] args) {
Random generator = new Random();
double value = generator.nextDouble();
if (value < 0.5) {
System.out.printf(“Heads\n”);
}
else {
System.out.printf(“Tails\n”);
}
}
Object to create random numbers
23
Pause…
Write a Java program to read a student’s
mark for a test from the keyboard and
display the corresponding letter grade.
Mark Letter grade
>=80 A
>=70 but < 80 B
>= 60 but < 70 C
>=50 but less than 60 D
<50 E
If-statement: 2-sort
▪Dry run the following program. What does it do?
import java.util.Scanner;
public class TwoSort {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); A Compare-
double a = in.nextDouble(); and-
Exchange
double b = in.nextDouble();
operation
System.out.printf(“a = %.2f\n”, a);
System.out.printf(“b = %.2f\n”, b);
if (a > b) { double t = a; a = b; b = t; }
System.out.printf(“a = %.2f\n”, a);
System.out.printf(“b = %.2f\n”, b);
} Make a smaller than b
}
25
If-statement: 3-sort
▪ Put statements to get a, b, and c in ascending order.
import java.util.Scanner;
public class ThreeSort {
public static void main(String[] args) {
Scanner in = new Scanner(System.in); Make a smaller than b
double a = in.nextDouble();
double b = in.nextDouble();
double c = in.nextDouble();
if (a > b) { double t = a; a = b; b = t; }
if (a > c) { double t = a; a = c; c = t; } Make a smaller
if (b > c) { double t = c; c = b; b = t; } than both b and c
System.out.printf(“a = %.2f\n”, a);
System.out.printf(“b = %.2f\n”, b);
System.out.printf(“c = %.2f\n”, c); Make b smaller than c
}
}
26
Summary
❑ Boolean expressions are used to make decisions in our
program
❑ Selection statements are used to selectively execute
statements based on the value of a Boolean expression
.
27
Object Oriented Programming T ALLMAN NKGAU
JAVA REVIEW
‣ Booleans
‣ Selection/Conditionals
http:http://horstmann.com/bjlo/index.html