Module 3
Module 3
Chapter 3
Introduction
Decision making and conditional statement allow you to control the flow of your
program's execu`tion. If left unchecked by control-flow statements, a program's logic will flow
through statements from left to right, and top to bottom. While some very simple programs can be
written with only this unidirectional flow, and while some flow can be controlled by using
operators to regulate precedence of operations, most of the power and utility of any programming
language comes from its ability to change statement order with structures and loops.
Learning Outcomes:
Flowchart Structure
Programmers often use a flowchart, a tool that helps them plan a program’s logic in
diagram form, as a series of shapes connected by arrows. There are two types of logical structure;
sequence structure and decision structure. The diagrams below show the structure
representation.
expressions. In Java, (and other programming languages like Python and C/C++/C#) decision
structures begin with the reserved word if.
Relational Operators
A relational operator, also called a comparison operator compares the values of two
operands based on a certain condition and returns a boolean value: True or False. These are often
used to create a test expression that controls program flow. This type of expression is also known
as Boolean expression because they create a Boolean answer or value when evaluated. The table
below lists the six common relational operators that give a Boolean value by comparing (showing
the relationship) between two operands.
Part I. True or False. Directions: Read each statement carefully, write TRUE if the
statement is correct otherwise write FALSE. Write your answer on the space provided before the
number. (1 point each)
_______1. The expression op1 == op2 is true if op1 is equal to op2.
_______2. The expression op1 <= op2 is true if op1 is less than to op2.
Part II. Multiple Choice. Directions: Select the letter of the correct answer and write on
the space provided before the number. (1 point each)
Object-Oriented Programming
_______3. It is a code structure where the statements are executed in sequence, without
branching off in another direction.
a. Sequence structure b. Sequence number c. Decision Structure
_______4. A control structure that allows different parts of a program to execute depending
on the exact situation.
a. Sequence structure b. Sequence number c. Decision Structure
_______5. The relational operator ‘<’ means ___.
a. greater than b. less than c. equal to
_______6. Evaluate the expression: (1 + 2) == 3
a. True b. False c. Unpredictable
_______7. Evaluate the expression: 25 < 5 * 5
a. True b. False c. Unpredictable
_______8. Evaluate the expression: (8 + 1) >= (2 * 3)
a. True b. False c. Unpredictable
_______9. Evaluate the expression: 10.0 + 0.10 < 11.0
a. True b. False c. Unpredictable
_______10. Evaluate the expression: 10.0 + 10.0/1.0 < 10.1
a. True b. False c. Unpredictable
Part III. Directions: Evaluate the following expression. Write your answer on the space
provided before the number. (1 point each)
where: a=5 b = 10 c= 15
__________1. a>b __________6. b <= c
__________2. a<b __________7. a >= b
__________3. a == b __________8. (b + c) == a
__________4. (b + c) > a __________9. c == c
__________5. c != (b-a) __________10. b >= (c-a)
Thinking Box:
Now check your answers against the Answer key. If you got atleast 95% of the items
correctly, proceed to the next Activity. If not, carefully review the lessons to help
you understand the concepts better. Concentrate on the parts that cover the
questions you missed. After this, you are very much ready to proceed to the next
learning activity.
In this lesson, Teaching and learning is mediated through the use of technology like print,
audio, video and the internet. Students interact with their instructors and each other through
virtual classrooms, email, and web conferencing. For the online modality, the Virtual Classroom
shall be used for the purpose of delivering a lecture and allowing a synchronous discussion with
the students. For the remote modality, Self-directed (SeDI) a learning management system shall
Object-Oriented Programming
be used to upload the module and to allow asynchronous discussion with the students. This will
also be used as platform for the submission of the requirements.
ASSESSMENT TASK
Create a Java Program that will display results based on the declared integers:
number1 = 50, number2 = 70 and number3 = 100. Use some of the relational
operators to provide Boolean results.
Integers:
number1 = 50
number2 = 70
number3 = 100
Truth Table:
number1 > number2 = False
number1 >= number3 = True
number2 < number1 = False
number2 <= number3 = True
number3 == number1 = False
number3 != number2 = True
Logical Operators
Logical operators are operators that determine if a particular condition is satisfied. The
three basic logical operators are and, or, and not. The logical operators compare Boolean
expressions and return a Boolean result. The and and or operators take two operands, and the not
operator takes a single operand.
There are two kinds of logical operators: bitwise logical operators and short-circuit
logical operators.
Bitwise logical operators manipulate the bits of an integer (byte, short, char, int, long)
value.
Operator Operation Use
& and op1 & op1
| or op1 | op2
^ xor op1 ^ op2
! not (Boolean !op
inversion)
Object-Oriented Programming
Short-circuit logical operators operate on the Boolean types. The outcome of these
operators are Boolean (true or false).
The and operator is also known as a Boolean multiplication – meaning all of the
conditions must be TRUE. This means that no matter how many TRUE conditions are there, if
there is just one FALSE condition, then the result is FALSE. Here is the truth table for the
Boolean and (&&, &) operator.
Note: The basic difference between && and & operators: the && supports short-circuit
evaluation (or partial evaluations), while & does not.
The or (||) operator is also known as a Boolean addition. This means that one TRUE
condition is enough for the result to be TRUE. Here is the truth table for || or | operator:
Note: The basic difference between || and | operators: the || supports short-circuit evaluation (or
partial evaluations), while | doesn’t.
Object-Oriented Programming
The not (!) operator negates the result of any Boolean expression. Any expression that
evaluates as true become false when preceded by the not operator accordingly. The logical not
takes in one argument, wherein that argument can be an expression, variable or constant.
Condition1 Result
True False
False True
Part I. True or False. Directions: Read each statement carefully; Write TRUE if the
statement is correct otherwise write FALSE. Write your answer on the space provided before the
number. (1 point each)
______1. Logical operator deals with connecting the Boolean values.
______2. The operator used for Short-circuit logical OR is &&.
______3. The operator used for Short-circuit logical AND is ||.
Part II. Multiple Choice. Directions: Select the letter of the correct answer and write
your answer on the space provided before the number. (1 point each)
______4. Used to combine more than one condition that may be true or false.
a. Short-circuit logical operator b. Logical operator
c. Bitwise logical operator
______5. Manipulate the bits of an integer (byte, short, char, int, long) value.
a. Short-circuit logical operator b. Logical operator
c. Bitwise logical operator
Part III. Directions: Evaluate the following expression. Write your answer on the space
provided before the number. (2 points each)
Where: a = 50 b = 25 c= 15
______1. (a > b)&& (a > b)
______2. (a == b) || (b + c)< c
______3. (c < b) && (b > a)
______4. (a < b) || (b > a)
______5. c != (a - b)
Object-Oriented Programming
Part IV. Directions. Trace the output produced by the following statements. Write your
answer on the space provided. (5 points each)
Int x = 3;
System.out.println (true && false); Answer: _________________________
System.out.println (true || false); _________________________
System.out.println (true || (x>0)); _________________________
Part V. Truth Table. Evaluate the following operands. Write the results on the space
provided. (1 point each)
B. Boolean OR operator
Operand 1 Result
True 1. _____________
False 2. _____________
Thinking Box:
Now check your answers against the Answer key. If you got atleast 95% of the items
correctly, proceed to the next Activity. If not, carefully review the lessons to help
you understand the concepts better. Concentrate on the parts that cover the
questions you missed. After this, you are very much ready to proceed to the next
learning activity.
Object-Oriented Programming
In this lesson, Teaching and learning is mediated through the use of technology like print,
audio, video and the internet. Students interact with their instructors and each other through
virtual classrooms, email, and web conferencing. For the online modality, the Virtual Classroom
shall be used for the purpose of delivering a lecture and allowing a synchronous discussion with
the students. For the remote modality, Self-directed (SeDI) a learning management system shall
be used to upload the module and to allow asynchronous discussion with the students. This will
also be used as platform for the submission of the requirements.
ASSESSMENT TASK
Make a Java program that will satisfy the condition set in the scenario presented below
using the logical AND operator.
For a college BSIT student to graduate, he or she needs to pass all subjects AND to
complete the capstone project. Using this scenario, let:
Make a Java program that will satisfy the condition set in the scenario presented below
using the logical OR operator.
For the Computer Club’s event to be approved, the proposal must be signed either by
COLLEGE DEAN OR PROGRAM CHAIR. Using this scenario, let:
Object-Oriented Programming
Make a Java program that will satisfy the condition set below using the logical NOT
operator.
Decision control structures are Java statements that allow us to select and execute
specific blocks of code while skipping other sections.
if–else statement
nested if–else/ if-else if statement
Use switch, continue, and break statements.
The if-else statement is used when we want to execute a certain statement if a condition is
true, and a different statement if the condition is false.
True False
boolean_expression
Statement Statement
if ( boolean_expression ) {
statement1;
statement2;
. . .
}Else{
statement1;
statement2;
...
}
Object-Oriented Programming
Example:
int grade = 79;
if ( grade > 75 ) {
System.out.println(“Congratulations!”);
System.out.println(“ You Passed!”);
} else {
System.out.println(“Sorry you failed”);
}
Using the nested if-else statements
Within an if or an else statement, you can include other if and else structures. Statements
in which an if structure is contained inside another if structure commonly are called nested if
statements. Nested if statements are particularly useful when two conditions must be met before
some action is taken.
True False
Boolean_expr1
Statement Statement
if( boolean_expression1 ){
statement1;
} else if ( boolean_expression2 ){
statement2;
} else {
statement3;
}
Example:
} else {
System.out.println(“Sorry you failed”);
}
Part I. Multiple Choice. Directions: Read each statement carefully, select the letter of
the correct answer and write your answer on the space provided. (2 points each)
_______4. Fill in the blank, so that students under 21 years are offered Grape Soda.
if(age ____ 21){
System.out.println(“How about a Brew?”);
}else{
System.out.println(“Care for some Grape Soda?”);}
a. <= b. == c. != d. >=
_______5. Fill-in the blank, so that students with grade greater than or equal to 75 will
pass the course.
if (grade _____ 75){
System.out.println (“You passed”);
}else{
System.out.println (“Sorry, you failed”);}
a. < b. == c. != d. >=
Part II. Directions. Trace the output of the following code fragments. Write your answer
on the space provided. (5 points each)
Object-Oriented Programming
Output: ___________________________________________________
Output: ___________________________________________________
Thinking Box:
Now check your answers against the Answer key. If you got atleast 95% of the items
correctly, proceed to the next Activity. If not, carefully review the lessons to help
you understand the concepts better. Concentrate on the parts that cover the
questions you missed. After this, you are very much ready to proceed to the next
learning activity.
In this lesson, Teaching and learning is mediated through the use of technology like print,
audio, video and the internet. Students interact with their instructors and each other through
virtual classrooms, email, and web conferencing. For the online modality, the Virtual Classroom
shall be used for the purpose of delivering a lecture and allowing a synchronous discussion with
the students. For the remote modality, Self-directed (SeDI) a learning management system shall
be used to upload the module and to allow asynchronous discussion with the students. This will
also be used as platform for the submission of the requirements.
ASSESSMENT TASK
Write a Java application that asks the user to input two numbers. If the first
number entered is greater than the second number, the program should print the message
“The first number is greater”, else it should print the message “The first number is
smaller”. And if the two numbers entered are equal, it will display “invalid”.
1. Write a Java application that asks a user to enter an IQ score. If the score is a
number less than 0 or greater than 200, issue an error message; otherwise,
issue an “Above average” for scores over 100, “Average” for score at 100 or
“Below average” for scores under 100.
2. Supposed a number is a variable of type int that has been given a value.
Write a nested if-else statements that outputs the word “High” if number is
greater than 10, “Low” if number is less than 5, and “So-so” if number is
anything else.
True
Case_Selector1 Block 1
Statement Break
False
True Block 2
Case_Selector2 Break
Statement
False
True Block 3
Case_Selector3
Statement Break
False
Default
switch ( switch_expression ) {
case case_selector1:
statement1;
statement2;
break;
case case_selector2:
statement1;
statement2;
break;
default:
statement1;
statement2;
}
where:
switch_expression - is an integer or character expression
case_selector1 and 2 - are unique integer or character constants
When a switch is encountered: It will first evaluate the switch_expression, and jumps to
the case whose selector matches the value of the expression. The program executes the statements
in order from that point on until a break statement is encountered, skipping then to the first
statement after the end of the switch structure.
If none of the cases are satisfied, the default block is executed. Take note however, that
the default part is optional. A switch statement can have no default block.
Notes:
When a case in a switch statement has been matched, all the statements associated with
that case are executed. Not only that, the statements associated with the succeeding cases
are also executed.
To prevent the program from executing statements in the subsequent cases, we use a
break statement as our last statement.
Directions. Trace the output of the following code fragments. Write your answer on the space
provided. (5 points each)
}
Output:
_______________________________________________________
_______________________________________________________
_______________________________________________________
2. Suppose you change the code in Question #1 so that the first line is the following:
int code = 1;
What output would be produced?
Output:
_______________________________________________________
_______________________________________________________
_______________________________________________________
Output:
_______________________________________________________
_______________________________________________________
_______________________________________________________
int key = 1;
switch (key + 1)
{
case 1:
System.out.println (“Cake”);
break;
case 2:
System.out.println (“Pie”);
break;
case 3:
System.out.println (“Ice cream”);
break;
case 4:
System.out.println (“Cookies”);
break;
Object-Oriented Programming
default:
System.out.println (“Diet time”);
}
Output:
_______________________________________________________
_______________________________________________________
_______________________________________________________
5. Supposed you change the code in Question #4 so that the first line is the following:
int key = 3;
What output would be produced?
Output:
_______________________________________________________
_______________________________________________________
_______________________________________________________
Thinking Box:
Now check your answers against the Answer key. If you got atleast 95% of the items
correctly, proceed to the next Activity. If not, carefully review the lessons to help
you understand the concepts better. Concentrate on the parts that cover the
questions you missed. After this, you are very much ready to proceed to the next
learning activity.
In this lesson, Teaching and learning is mediated through the use of technology like print,
audio, video and the internet. Students interact with their instructors and each other through
virtual classrooms, email, and web conferencing. For the online modality, the Virtual Classroom
shall be used for the purpose of delivering a lecture and allowing a synchronous discussion with
the students. For the remote modality, Self-directed (SeDI) a learning management system shall
be used to upload the module and to allow asynchronous discussion with the students. This will
also be used as platform for the submission of the requirements.
ASSESSMENT TASK
A. Write an application that prompts user for two integers and then prompts the user to enter
an option. If the choice is 1, add the two integers. If it is 2, subtract the second integer
from the first. If it is 3, multiply the integers. Display the results of the arithmetic.
Object-Oriented Programming
B. Write a program for a furniture company; the program determines the price of a table.
Ask the user to choose 1 for pine, 2 for oak or 3 for mahogany. The output is the name of
the wood chosen as well as the price of the table. Pine table cost Php100, oak tables cost
Php250 and mahogany table cost Php500. If the user enters invalid wood code set the
price to 0.
Loop
A loop is a structure that allows repeated execution of a block of statements called loop
body. Within a looping structure, a Boolean expression is evaluated. As long as the Boolean
expression is true, the statements in the loop body continue to execute. The diagram presented
below shows the loop structure.
A while loop can be used to execute a body of statements continually as long as the
Boolean expression that controls the entry into the loop continues to be true. The syntax for the
while loop is as follows:
The statements inside the while loop are executed as long as the boolean_expression
evaluates to true.
int i = 0;
while ( i < 4 ) {
System.out.print (i);
i++;
}
The sample code shown will print 4321 on the screen. Take note that if the line
containing the statement i--; is removed, this will result to an infinite loop, or a loop that does not
terminate. Therefore, when using while loops or any kind of repetition control structures, make
sure that you add some statements that will allow your loop to terminate at some point.
The do-while loop is a variation of the while loop. The statements inside a do-while loop
are executed several times as long as the condition is satisfied. The syntax for the do-while loop
is as follows:
do{
//loop body
statement1;
statement2;
…
}while (boolean_expression);
The statements inside the do-while loop are first executed, and then the condition in the
boolean_expression part is evaluated. If this evaluates to true, the statement inside the do-while
loop are executed again.
Note: The main difference between a while and do-while loop is that, the statements inside a do-
while loop are executed at least once.
int i = 8;
do{
System.out.print(i);
i--;}while(i>0);
Using a for loop
A for loop is used when a definite number of loop iterations is required. Although you
can meet this requirement by using a while loop, the for loop provides you a shorthand notation
for this type of loop. The syntax for the for loop is:
for (InitializationExpression; LoopCondition; StepExpression)
{
statement1;
statement2;
…
}
Object-Oriented Programming
Where:
InitializationExpression Initialize the loop variable e.g. int value = 0
LoopCondition Compares the loop variable to e.g. value < 5
some limit value
StepExpression Updates the loop variable e.g. value++
Directions: Trace the output of the following code fragments. Write your answer on the space
provided.
1. What output will be produced by the following code?
Output:
for ( int n = 4; n > 0; n-- ){ __________________________
System.out.print (n); __________________________
} __________________________
__________________________
2. What output will be produced by the following code?
Output:
for (int a = 5; a < 8; a++){ __________________________
System.out.print (a); __________________________
} __________________________
__________________________
3. What output will be produced by the following code?
Output:
double test; __________________________
for (test = 0; test < 2; test = test + 0.5){ __________________________
System.out.print (test): __________________________
} __________________________
int time;
for (time=1; time <=4; time++){
System.out.println (“One more time.”);
}
Output:
__________________________
__________________________
__________________________
Thinking Box:
Now check your answers against the Answer key. If you got atleast 95% of the items
correctly, proceed to the next Activity. If not, carefully review the lessons to help
you understand the concepts better. Concentrate on the parts that cover the
questions you missed. After this, you are very much ready to proceed to the next
learning activity.
In this lesson, Teaching and learning is mediated through the use of technology like print,
audio, video and the internet. Students interact with their instructors and each other through
Object-Oriented Programming
virtual classrooms, email, and web conferencing. For the online modality, the Virtual Classroom
shall be used for the purpose of delivering a lecture and allowing a synchronous discussion with
the students. For the remote modality, Self-directed (SeDI) a learning management system shall
be used to upload the module and to allow asynchronous discussion with the students. This will
also be used as platform for the submission of the requirements.
ASSESSMENT TASK
A. Using the while loop statement, create a program that prints your name a Fifty times.
B. Using the do-while loop statement, create a program that prints your name a hundred
times.
C. Write a program using the for loop that will output the phrase “I love Programming” to
the screen 10 times. Also, give any declarations or initializing statements that are needed.
D. Write a for loop statement that writes out the even numbers 2, 4, 6, 8, and 10. The output
should put each number on a separate line.
E. Using a for loop, write an application that sums the integers from 1 to 50 (that is, 1 + 2 +
3 + …. + 50).
References:
1. https://www.programiz.com/java-programming
2. https://www.javatpoint.com
3. https://beginnersbook.com/2017
4. https://www.w3schools.com/java
5. https://www.geeksforgeeks.org
6. https://www.tutorialspoint.com/java