0% found this document useful (0 votes)
60 views22 pages

Module 3

This document discusses decision making and conditional statements in object-oriented programming. It introduces sequence and decision structures using flowcharts. Relational operators like <, >, ==, etc. are used to compare values and return Boolean results. Logical operators like &&, ||, and ! are also discussed. The learning outcomes include using if/else statements, loops, and relational operators to control program flow based on conditions. Sample code is provided to demonstrate relational operators, and an assessment task involves creating a program using relational operators on integers.

Uploaded by

Ronald Rivera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views22 pages

Module 3

This document discusses decision making and conditional statements in object-oriented programming. It introduces sequence and decision structures using flowcharts. Relational operators like <, >, ==, etc. are used to compare values and return Boolean results. Logical operators like &&, ||, and ! are also discussed. The learning outcomes include using if/else statements, loops, and relational operators to control program flow based on conditions. Sample code is provided to demonstrate relational operators, and an assessment task involves creating a program using relational operators on integers.

Uploaded by

Ronald Rivera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Object-Oriented Programming

Chapter 3

Decision Making and Conditional Statement

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:

At the end of the chapter the students should be able:


 Use relational and equality operators.
 Use logical and comparison operators.
 Use if..else statements.
 Use switch, continue, and break statements.
 Use while and do..while loops.
 Use for loops.

Start your lesson here.

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.

Sequence Structure Decision Structure


To differentiate,
Sequence Structure is a code structure where the statements are executed in sequence,
without branching off in another direction
while the Decision Structure is a control structure that allows different parts of a
program to execute depending on the exact situation. Usually, decisions are controlled by boolean
Object-Oriented Programming

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.

Operator Description True example False example


< Less than 5 < 10 10 < 5
> Greater than 10 > 5 5 > 10
== Equal to 10 == 10 5 == 10
<= Less than or equal to 5 <= 5 10 <= 5
>= Greater than or equal to 10 >= 5 5 >= 10
!= Not equal to 5 != 10 5 != 5

The table below shows examples and its corresponding results.

Operator Use Result


> op1 > op2 True if op1 is greater than op2, otherwise false
>= op1 >= op2 True if op1 is greater than equal to op2, otherwise false
< op1 < op2 True if op1 is less than op2, otherwise false
<= op1 <= op2 True if op1 is less than equal to op2, otherwise false
== op1 == op2 True if op1 and op2 are equal, otherwise false
!= op1 != op2 True if op1 and op2 are not equal, otherwise false

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.

Recommended Learning Materials and Resources


To supplement the lesson in this module, you may visit the following links:
 https://www.programiz.com/java-programming
 https://www.javatpoint.com
 https://beginnersbook.com/2017

Flexible Teaching Learning Modality (FTLM) adapted

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

A. Using relational Operators

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.

The expected Output is:

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

Start your lesson here.

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

Operator Name Usage Outcome


&& Short-circuit logical AND op1 && op2 True if op1 and op2 are both true,
otherwise false, Conditionally
evaluates op2.
|| Short-circuit logical OR op1 || op2 True if either op1 or op2 is true,
otherwise false. Conditionally
evaluates op2.

Note: Bitwise logical operators always evaluate bot


h op1 and op2 before returning an answer unlike Short-circuit logical operators that if the op1 is
false, the operator never evaluates op2 because the result of the operator will be false regardless
of the value of op2.

Using Boolean and (&&) Operator

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.

Condition1 Condition 2 Result


True True True
True False False
False True False
False False False

Note: The basic difference between && and & operators: the && supports short-circuit
evaluation (or partial evaluations), while & does not.

Using Boolean or (||) Operator

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:

Condition1 Condition 2 Result


True True True
True False True
False True True
False False False

Note: The basic difference between || and | operators: the || supports short-circuit evaluation (or
partial evaluations), while | doesn’t.
Object-Oriented Programming

Using Boolean not (|!) Operator

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.

Here is the truth table for not (!)operator:

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)

1. What output is produced by the following statements?

System.out.println (false); Answer: _________________________


System.out.println (7 < 0); _________________________
System.out.println (7 > 0); _________________________
int n =7; _________________________
System.out.println (n > 0); _________________________

2. What is the output of the following statement?

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)

A. Boolean AND operator

Operand 1 Operand 2 Result


True True 1. _____________
True False 2. _____________
False True 3. _____________
False False 4. _____________

B. Boolean OR operator

Operand 1 Operand 2 Result


True True 1. _____________
True False 2. _____________
False True 3. _____________
False False 4. _____________

C. Boolean NOT 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

Recommended Learning Materials and Resources


To supplement the lesson in this module, you may visit the following links:
 https://www.programiz.com/java-programming
 https://www.javatpoint.com
 https://beginnersbook.com/2017
 https://www.w3schools.com/java

Flexible Teaching Learning Modality (FTLM) adapted

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. Using Logical and (&&) Operator

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:

Condition 1 = Passed all subjects


Condition 2 = Completed the capstone project
Result: Graduate

B. Using the logical or (||) operator

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

Condition1 = Signature of the College Dean


Condition2 = Signature of the Program Chair
Result: Event is APPROVED

C. Using logical not (!) Operator

Make a Java program that will satisfy the condition set below using the logical NOT
operator.

If color is not ORANGE display message “You don’t belong”

Start your lesson here.

Decision Control Structures

Decision control structures are Java statements that allow us to select and execute
specific blocks of code while skipping other sections.

These are the three basic types of decision control structures:

 if–else statement
 nested if–else/ if-else if statement
 Use switch, continue, and break statements.

Using the if-else statement

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.

The flowchart of the if-else statement is:


If-Else Statement Flowchart

True False
boolean_expression

Statement Statement

The if-else statement has the form/syntax:

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.

The flowchart of the nested if–else/ if-else if statement is:


If-Else if Statement Flowchart

True False
Boolean_expr1

Statement True False


Boolean_expr
2

Statement Statement

The nested if–else/ if-else if statement has the form/syntax:

if( boolean_expression1 ){
statement1;
} else if ( boolean_expression2 ){
statement2;
} else {
statement3;
}

Example:

int grade = 68;


if ( grade > 90 ) {
System.out.println(“Very Good!”);
} else if ( grade > 60 ) {
System.out.println(“Good!”);
Object-Oriented Programming

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

_______1. What does the following code fragment display?


int height = 10;
if(height <= 12){
System.out.print(“Low bridge: ”);
System.out.println(“proceed with caution.”);}
a. Nothing is displayed b. Low bridge:
c. proceed with caution . d. Low bridge: proceed with caution.
_______2. What does the following code fragment display?
int height = 13;
if(height <= 12){
System.out.print(“Low bridge: ”);
System.out.println(“proceed with caution.”);}
a. Nothing is displayed b. Low bridge:
c. proceed with caution . d. Low bridge: proceed with caution.

_______3. What does the following code fragment display?


int depth = 8;
if(depth >= 8) {
System.out.print(“Danger: ”);
System.out.print(“deep water. ”);
}
System.out.println(“No swimming allowed.”);
a. Danger: b. Danger: deep water. No swimming allowed.
c. Danger: deep water. d. deep water. No swimming allowed.

_______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

1. What output is produced by the following codes?

int time = 2, tide =3;


if (time + tide) > 6
System.out.println (“Time and tide wait for no one.”);
else
System.out.println (“Tide and time wait for me.”);

Output: ___________________________________________________

2. What output is produced by the following codes?

int time = 4, tide =3;


if (time + tide > 6)
System.out.println (“Time and tide wait for no one.”);
else
System.out.println (“Tide and time wait for me.”);

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.

Recommended Learning Materials and Resources


To supplement the lesson in this module, you may visit the following links:
 http://iiti.ac.in/people/~tanimad/JavaTheCompleteReference.pdf
 http://www.java.sun.com
 www.Callingallinnovators.com

Flexible Teaching Learning Modality (FTLM) adapted

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. Using if-else statement


Object-Oriented Programming

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

B. Using Nested if-else statement

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.

Start your lesson here.

The Switch statement

The switch statement allows branching on multiple outcomes. It is a selection statement


that means when used, it can select one value among many values. Also, an alternative to use the
series of nested if statements is to use the switch statement.

The diagram below shows the flowchart of the switch statement.


Object-Oriented Programming

Switch Statement Flowchart

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

The switch statement has the form/syntax:

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.

Example for switch

public class grade


{
public static void main (String [] args)
{
Object-Oriented Programming

int grade = 90;


switch (grade){
case 100:
System.out.println (“Excellent!”);
break;
case 90:
System.out.println (“Good job!”);
break;
case 80:
System.out.println (“Study harder!);
break;
default
System.out.println (“Sorry, you failed.”);
}
}
}

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)

1. What output is produced by the following codes?


int code = 2;
switch (code)
{
case 1:
System.out.println (“Hello”);
break;
case 3:
System.out.println (“Good bye”);
break;
default:
System.out.println (“Till we meet again”);
break;
Object-Oriented Programming

}
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:
_______________________________________________________
_______________________________________________________
_______________________________________________________

3. What output is produced by the following codes?


char letter = ‘B”;
switch (letter)
{
case: ‘A’:
case: ‘a’:
System.out.println (“Some kind of A”);
case: ‘B’:
case: ‘b’:
System.out.println (“Some kind of B”);
break;
default:
System.out.println (“Something else”);
break;
}

Output:
_______________________________________________________
_______________________________________________________
_______________________________________________________

4. What output is produced by the following codes?

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.

Recommended Learning Materials and Resources


To supplement the lesson in this module, you may visit the following links:
 https://www.programiz.com/java-programming
 https://www.javatpoint.com
 https://beginnersbook.com/2017
 https://www.w3schools.com/java

Flexible Teaching Learning Modality (FTLM) adapted

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.

Start your lesson here.

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.

Using a while loop

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:

while (loop boolean_expression) {


//loop body
statement(s);
}
Object-Oriented Programming

The statements inside the while loop are executed as long as the boolean_expression
evaluates to true.

For example, given the code fragment,

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.

Using a do-while loop

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

A simple example of the for loop is,


int i;
for (i = 0; i < 5; i++) {
System.out.print ( i );
}

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): __________________________
} __________________________

4. What output will be produced by the following code?

int count, innerCount;


for (count= 0; count <= 3; count++){
Object-Oriented Programming

for (innerCount=0; innerCount < count; innerCount++){


System.out.print (innerCount);
}
}
Output:
__________________________
__________________________
__________________________
5. What output will be produced by the following code?

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.

Recommended Learning Materials and Resources


To supplement the lesson in this module, you may visit the following links:
 https://www.programiz.com/java-programming
 https://www.javatpoint.com
 https://beginnersbook.com/2017
 https://www.w3schools.com/java

Flexible Teaching Learning Modality (FTLM) adapted

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

You might also like