[go: up one dir, main page]

0% found this document useful (0 votes)
8 views9 pages

LM 03 Java Loops

Uploaded by

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

LM 03 Java Loops

Uploaded by

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

CS 211

OBJECT-ORIENTED
Programming
LEARNING MODULE

Prepared by:
Ms. FATIMA MARIE P. AGDON
Mr. JANCYRILL L. MENDOZA
Java Loops
MODULE THREE
In this tutorial, the students will learn how to use, importance, and advantages of the iter-
ation structure, also known as loops in Java, with the examples provided.

What are Loops?


Adding two numbers should be easy, or even ten. But what if you are to add the
numbers from 1 to some upper bound, represented by variable n? Assume that you
don’t have an idea on the formula. Suppose, n is equal to 7. You have two options:

A. Add the numbers 1, 2, 3, 4, 5, 6, and 7


B. Add the numbers from 7, then 6, 5, 4, 3, 2, and 1

Handling this situation will be—first, in Option A, a variable will begin with some val-
ue, and step-by-step, the variable increases by 1, and gets repeated many times until
the point of the upper bound is reached, in our example is 7. For Option B, the value
starts at 7, reduces by 1 in every step, until the value reaches 1.

And I guess you’re thinking on how to make it happen. That is when loop comes in
handy.

Types of Loop
The previous scenario describes repeated addition, or subtraction, wherein the same
statement is being repeated many times over, and at some point has to stop. That is
what we call an iteration, or some are familiar with its other term, loops. Java has
four forms of the loop construct, such as: while loop, for loop, do-while loop, and
for-each loop.

Regardless of construct, loops have the same major components, such as:

• A condition that checks whether the repetition still needs to be executed.


• An expression or statement that changes the value of the variable
used in the condition above. This “change” should eventually lead to
breaking the loop, and happens when the condition evaluates to false.

That being said, as long as the condition in the loop construct evaluates to true, the
repetition or iteration continues, and makes a halt when the condition evalu-
ates to false.

Now, let’s find out the different kinds of loop constructs in Java.
The while Loop
The while loop iterates through a block of code as long as a specified condition
is true:

The code snippet shows that it is similar to an if-statement, but instead of using the if
keyword, it is replaced by while. It means that the statement will be executed
many times over, as long as the condition in the parentheses evaluates to false.
The statements inside the curly braces could be any valid Java statement, for
example, assignment statements with computations, if-statements, and even loops
themselves.

Going back to our scenario earlier, we would need the upper bound value, represent-
ed by the variable up_bound, and a variable to hold the initial value 1, and will be
named as ctr, short for counter, because its purpose is to count the iterations from 1
all the way to up_bound. Another variable for the result will be initialized, and let’s
call it sum.

Then, we set up the while loop. A condition must be constructed and that state-
ment that would lead to break the iteration.

In this scenario, recall that ctr begins in 1. As it progresses, it has to turn to 2, then 3,
then 4, all the way to up_bound. The ctr++ means that ctr is being added 1
(remember Lesson 1?) as it meets the condition in the parentheses. The counter vari-
able will be incremented, and the while loop is responsible for repeating ctr++ many
times over.

But wait, there’s more. What about sum? In this case, think about how much should
sum accumulate—if you’re thinking the value of ctr, then you’re right! Remember, ctr
starts at 1, then becomes 2, then 3, all the way to the value of up_bound.
How, then, do we let sum accumulate by ctr? See for yourself!

This means that we are updating the value of sum, remember that the equal sign
is an assignment operator—it exactly updates the value of the variable on the
left-hand side, in this case, sum. Meanwhile, the right-hand side takes the current
value of sum and adds the value of ctr to it. It is the result assigned to sum, there-
by updating its value. That is what accumulation is all about. Now, let’s put together
the solution!

Now, let us try to let ctr begin with up_bound, and should reduce repeatedly by 1, un-
til the value 1 is reached. Find out if it resulted to the same output as before.
Different operations, but it still landed the same result. Go explore!

The for Loop


The for loop is used if you know exactly the number of times you want to loop
through a block of code.

There are three components of for-loop. First, the initializer, which is once execut-
ed at the start of the loop. Even if the loop is to iterate a thousand times, the initial-
izer will be executed once, hence its name. Second, the condition. It behaves simi-
larly with how the condition in the while loop behaves. Third, the iterator, which
performs the updates on certain variables that were used in the loop.

Going back to the while loop situation, the ctr++ is the iterator in the for loop.
Now, let us utilize for loop in our while loop example:

Let’s test it out:

Check, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 in your calculators, or actually, you can


mentally do it! If it resulted to 55, then we made it. We’re on the right track.

Additional reading: Go to our CodeChum class, and test out the different code examples
for the for-loop.
The do-while Loop
In do-while loop, repetition is achieved by doing or executing the statement in
the loop first, before checking the condition. Unlike with while and for loops,
where the condition is checked first before execution of the statements inside the
loop. That being said, the statements in the loop get executed at least once.

This is how the do-while loop looks like:

Going to our example, how do we ensure that the user only enters a positive value
for up_bound? This means making sure that we let the user re-enter the input every
time up_bound is not positive. Check it below:

Through the utilization of a do-while loop in asking for the upper bound, the
up_bound is assured to be positive, when the program begins computing for the
summation from 1 to up_bound. The do-while is the most appropriate loop construct
for the situation since the asking for the input gets executed once.

Let’s spice things up a bit, shall we?


Nested Loop
A nested loop is when another loop exists in the body of another loop. For this, let
us consider this example:

In this example, there are two for loops. The first one, or the outer loop will be exe-
cuting the weeks, and then the second, which is the inner loop will be printing the
days. The outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates
7 times and prints the 7 days.

It is also possible to use one type of loop inside the body of another loop. For in-
stance, a for loop inside a while loop. In creating patterns like full pyramid, half pyra-
mid, inverted pyramid, so on, the nested loops can be used.

Break and Continue Statements


While working with loops, it is sometimes desirable to skip some statements inside
the loop or terminate the loop immediately without checking the test expression. The
break and continue are jump statements that can be applied to skip on one state-
ment to another.

The Java break Statement


You may already have an idea on how the break statement is used, after our discus-
sion of the conditionals. Break statements terminates the loop immediately, and the
control of the program will move to the next statement after the loop. Also, it may be
sometimes used in decision-making statements.

In this example, the break statement is used, hence when the value of idx reaches 5,
the loop stops, resulting the output to 1 2 3 4, each number separated by line breaks.
The Java continue Statement
If the break statement cuts the execution, the continue statement skips. It moves
to the end of the iteration, and then the test expression is evaluated, and the update
statement is evaluated in case of the for loop.

In the example, a for loop is used to print the value of idx in each iteration. You may
notice in Lines 7 and 8, that the continue statement is executed when the value of idx
becomes greater than 4 and less than 9. The print statement is skipped when idx val-
ues are 5, 6, 7, and 8.
break and continue Statements in Nested Loops
Look at the following representations of working of break and continue statements in
nested loops:

References
CodeChum. https://codechum.com
Programiz. https://programiz.com
W3Schools. https://www.w3schools.com/java/java_intro.asp

You might also like