Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

ITERATIVE STRUCTURE

Rueda Street, Calbayog City, Samar, Philippines | +63 (055) 533 9857 | main@nwssu.edu.ph | www.nwssu.edu.ph
Iterative Structure

• also known as loops


• fundamental programming constructs in Java
that allow you to repeat a code block multiple
times based on specified conditions
Three Types of Loops

• while,
• do...while,
• for
while loop
• The while loop evaluates the condition before
executing the code block.
• If the condition is true, the code block is
executed, and the loop continues.
• If the condition is false initially, the code block
is never executed.
while loop
do…while loop
• The do...while loop executes the code block
first and then evaluates the condition.
• If the condition is true, the loop continues, and
the code block is executed again.
• This loop type guarantees that the code block
is executed at least once.
do…while loop
for loop
• The for loop consists of three parts: initialization, condition,
and increment.
• The initialization is executed only once at the beginning.
• The condition is evaluated before each iteration, and if true,
the code block is executed.
• After each iteration, the increment is executed, and the
loop continues if the condition is still true.
for loop
Nested loop
Exercises : Find the Error

 Find the error in each of the following code


segments, and explain how to correct it:
1. ‘-

2.
19
Exercises
3.

4. ‘-

5.

20
Exercises
 Write a program using for loop statement that will
display a series of numbers from 1 to 10 in
ascending and descending order.
‘-
 Write a program using while loop that will display the
sum of all numbers based from the given positive
input.
 Write a program using do…while loop that will
display the following sequence of numbers. Sample
21
output: 500 400 300 200 100
 Repeatedly ask the user to input an integer and add
these all up while the value inputted is not yet 0.
After the user has inputted 0, print the final total
‘-
value on the next line.

22

You might also like