Repetition Sturcture - Looping JAVA ch3
Repetition Sturcture - Looping JAVA ch3
Loop Basics
• All programming languages provide statements to
create a loop. The loop is the basic component of a
repetition structure.
• These statements are a block of code, which under
certain conditions, will be executed repeatedly.
• In this section, we will introduce some basic ideas
about these structures.
• We will start with a simple illustration of a loop
shown.
This example uses a type of loop called a
Repeat...Until loop.
1 Declare Number As Integer
2 Repeat 3
3 Write "Please enter a number: "
4 Input Number
5 Write Number
6 Until Number == 0
7 Write "List Ended”
Iterations
• pretest loops
• post-test loops
The Do . . . While Loop
Declare Number As Integer
Do
Write "Enter a number: “
Input Number
Write Number
While Number != 0
Write "List Ended"
Pre-Test Loop
Stop
Using a Counter
5 3/4 times.
Set Count = Count + 1. This takes the old value, adds one to it,
and stores the new value where the old value was.
Using a Counter to Display the Squares of Numbers
• Declare PositiveInteger As Integer
• Declare Count As Integer
• Write "Please enter a positive integer: "
• Input PositiveInteger (5) count count^2
• Set Count = 1 1 1
• While Count <= PositiveInteger 2 4
• Write Count + " " + Countˆ2 3 9
• Set Count = Count + 1 4 16
• End While 5 25
Countdown
• Declare Count As Integer
• Set Count = 100
• Write "Countdown in . . . ";
• While Count > 0
• Write Count + " seconds"
• Set Count = Count − 1
• End While
• Write "Blastoff!"
The For Loop