New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]Week 10-12
REPETITION CONTROL STRUCTURE
In this module, you will learn about loop statements in Java, as well as techniques
for writing programs that process input and simulate activities in the real world.
Learning Outcomes:
At the end of the module, the student should be able to:
1. Understand how looping statement shorten codes on repetitive tasks;
2. Use do-while, while and for loop statements;
3. Simulate program with looping statement;
4. Construct program with looping statement within another looping statement.
Looping
Looping or repetition control structure is Java statements that allows to execute
blocks of code in a number of times. A looping statement have three types. The while, do-
while and for loops.
On a normal approach of the beginner in programming, there are some cases, for
example you need to display “I love you!” 3 times. A beginner who is just learning a
program will use 3 System.out.println(“I love you!”); to meet the requirements. The
program will looks like this:
How about if the requirements are to display 50 or 100 “I love you”? Are the programmer
write 50-100 System.out.println(“I love you!”);? Inefficient approach right? That is why
there are looping statements to address those issues.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
The while Statement
The while loop is a statement or block of statements that is repeated as long as the
condition is satisfied.
The while statement has the following syntax:
In general, looping statement has 3 parts. The first part is the declaration of a variable
or a counter to control the number of times the loop executes. The while loop statement
test the condition (the second part) before executing the statement/s under the statement
block. The statement/s inside the while loop including the update (the last part of a loop
which is to increment or decrement the variable) are executed as long the as the condition
is true. After executing the statement/s inside the block, it will loop back to the while
condition and test again. If the condition turns out to false, it will disregard the statement
block then it immediately proceed to <next statement> outside the block.
Let us now apply the while loop in the ILoveYou program:
From the example source code, let’s study how the looping occurs in the program:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
The ctr was declared to be our control variable in our program and has an initial
value of zero. The next step will evaluate the while condition. In the condition, it will ask if
the value of ctr is less than 3. Since, ctr=0, it is less than 3, the while condition turns out
to true and it will execute the statement System.out.println("I love you!");, and
display the message "I love you!" then update by incrementing by 1 the value of ctr.
The variable ctr now, has 1 value.
Once it reach the closing curly brace of while, it will force to loop back and evaluate
again the while condition.
Since the present value of ctr=1 and still less than 3 (1<3), the condition is true. It
will execute the statements and display "I love you!" for the second time, and
increment by 1 the ctr making ctr=2.
Then it will loop back and evaluate the condition of while. Is ctr less than 3 (2<3)?
The condition is true. It will execute the statement System.out.println("I love
you!");, and display the message "I love you!", for the third time and add 1 to ctr.
The ctr value is now 3. Closing curly braces is reached. Loop back to while(ctr<3)
statement.
Since ctr=3, it is not less than 3, the condition turns out to false. The false result
will disregard the statement block and execute statement (if any) outside it. Once it reach
the closing braces, the program terminates.
Here is the simulation of the program:
Accumulator/Counter: Output:
ctr (ctr<3?)
0 t I love you!
1 t I love you!
2 t I love you!
3 f
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]CHECK THE ASSESSMENT MODULE
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]The do-while Statement
The statements inside a do-while loop are executed at least once. However this
loop will produce the same result. Note, that you need to terminate the while (condition)
with semicolon.
The do-while statement has the following syntax:
The statements inside the do-while loop are first executed, and then the while
condition part is evaluated. If this evaluates to true, the statements inside the do-while loop
are executed again. (Note: if the while condition is true, remember to do the statement).
Let’s now implement the do-while loop. This time we will use a decrement operation
and change the condition with less than equal.
We declare the ctr as integer with a value of 3. The program immediately implement
the statements within the block of do-while. This is the part of the do-while where you can
execute statements at least once even if you have not yet encountered the while condition.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
The program will execute the System.out.println("I love you!");, and print “I
love you!”, then ctr will decrement by 1 and now the ctr has a value of 2.
After the program reach the closing brace of do, it evaluates the while condition.
Since ctr=2, it is greater than or equal 1(ctr>=1) that sets the condition into true. And since
it is true, it will loop back to do and implement the block statement.
The program will print “I love you!” in the second time, then decrement 1 from
ctr. the current value of ctr=1.
Then proceed to while condition. Is ctr>=1? The result is true. It will loop back to
do statement block and evaluate the System.out.println("I love you!");, and print
“I love you!”, then, deduct 1 to ctr; ctr now has value of zero.
Is ctr>=1? Obviously, it’s false because 0 is not greater than or equal to 1. The
program exits on the do-while block statement. And if there are no more instructions after
the do-while statement, the program terminates.
Here is the simulation of the program:
Accumulator/Counter: Output:
ctr (ctr>=1?)
3 I love you!
2 t I love you!
1 t I love you!
0 f
There is no True or False result here because the
while condition has not been encountered
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
Assessment 2:
CHECK THE ASSESSMENT MODULE
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]The for statement
The for looping statement is similar to while statement that allows execution of
statements under the block of statement as long as the condition is satisfied , and it has
the following syntax:
Here are a few examples on how for loop works:
Next is a for loop statement but in a while statement format:
Based on the program ForILoveYou1, let us try to analyze how this for loop works.
Step 1: The first statement under the for loop statement that will be evaluated is the
ctr=0; which is the assignment of the variable/identifier ctr.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
Step 2: From reading of the assigned variable, it will proceed to the for condition
which is the ctr<3. Since the condition is satisfied, means true, the
statements under the curly braces are now ready for evaluation.
Step 3: The program will display “I love you!”.
Step 4: After printing the “I love you!”, it will loop back to update and execute
the increment by of ctr. The value of the ctr is now 1.
Step 5: From the update part, it will go back and read the for condition, (ctr<3). The
result obviously turns to true.
Since condition is true, it will print again the “I love you!” in the second
time.
Then, it will loop back to update and increment the value of ctr. ctr is now 2.
It will test again the for condition (ctr<3). The result is still true. Then display
the “I love you!”, in the third time.
Loop back and implement the ctr++ that results to 3 as the present value of
ctr.
The program will test again the condition (ctr<3). The result turns out to
false, because 3 is not less than 3. Then, the program escapes the for loop
block.
Here is the exact flow on how for loop works:
It seems like for loop is complicated but it is mostly used by a programmer. But it’s
your choice which is easier and convenient to use. Simulation process is the same with
the while loop statement.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
Assessment 3:
CHECK THE ASSESSMENT MODULE
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected] Let’s have another working example: Design a program SquareCube that displays
the square and cube of an integer from 1 to n.
Sample Input/Output
Enter n: 3
Integer Square Cube
1 1 1
2 4 8
3 9 27
As we did before, we name first our program class with SquareCube. We include
the Scanner class to be used in the input of n.
Let us declare our input object for the Scanner class; integer n for the number we
will input.
Prompt message “Enter n: “ and convert the input number into an integer and assign
the value to n.
Print the header text before we generate the squares and cubes of our number
series.
On this case we need a counter that will increment as we proceed in generating the
values. Declare ctr on the declaration area. Since our generation of values starts with 1,
initialize ctr with 1.
Use while as our looping statement to do the computing and generating of values.
Our condition will be a comparison of ctr versus n. We need to check if ctr has already
reached the limit n in generating the squares and cubes of the numbers.
To compute for the square of the number, we multiply ctr with ctr. To compute for
the cube, we multiply ctr with ctr with ctr or simply the square of ctr with another ctr. We
name our accumulators with the same name: square and cube. Declare it on top of our
declaration area with initial value set to zero and data type int.
We are now ready to print the values of the square and cube on an integer. Display
the value ctr. Separate ctr value with a \t tab character for the square value. Do the same
thing for the cube value.
The generation of values does not end with 1 alone. On our sample input we need
to generate n with the value of 3. So our limit was set actually with 3.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
Increment ctr with ctr++. ctr now has a value of 2. That will set the whole block of
our while statement.
As the loop ends with the closing brace, it will evaluate again at the beginning of
our while statement if ctr is less than or equal to n.
Is ctr <= n? Is 2 <= 3? True. Implement again the block statements inside while.
square will have a new value 4 (2 multiply by 2). cube will have a value 8 (4 multiplied by
2).
Print again the new set of values with 2 as the value of ctr; 4 for the square; 8 for
the cube.
Increment ctr. ctr is now 3.
Loop back. Is 3 <= 3? True.
3 multiply by 3 is 9. That would be the value of square.
9 multiply by 3 is 27. That would be the value of cube.
Print 3, 9 and 27.
Increment ctr. ctr is now 4.
Test if ctr is less than or equal to n which is 3. 4 <= 3? False. The execution
proceeds outside the while loop. Since there is no more thing to do next, the program
terminates.
Below are the code and the output of our program:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
Assignment 1:
Based on the example SquareCube program, create a program OddSquareCube
that produces the output below. Maximum of 3 System.out.println() or System.out.print()
should be used in the solution:
Implementing Conditional Statement to Looping Statement
One way of testing the capability of the student if you are improving in programming
is implementing conditional statement to a looping statement. The next example will design
a program called SumOdd that will display the odd numbers from last number to 1 and
display its sum at the end.
Sample Input/Output:
Enter last number: 15
15 13 11 9 7 5 3 1
Sum is 64
Name our program SumOdd. Call our Scanner class for the input. Declare input
as our object for the Scanner class and lastNum for the inputted last number as int with
initial value of 0.
Write the prompt input message. Assign the inputted number to lastNum.
This time we will use a for loop statement to generate the odd values. We will assign
the value of the lastNum to counter ctrNum. Test ctrNum if it greater than or equal to 1.
Decrement ctrNum.
Do not forget to declare ctrNum at the declaration area. Initialize it with 0.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
To separate our output to the input area, we type System.out.println() to move to
the next line.
Inside the block of the looping statement, we need to test if the number is odd or
even. We could do this if a number is divisible by 2 by lastNum modulus of 2. If the
operation equals to 1, then, the number is odd. We could do this by using a boolean
variable named oddNum.
We test it by statement: oddNum = ctrNum % 2 ==1.
Don’t forget to declare the boolean variable oddNum at the declaration area with
initial value of false.
We are testing ctrNum if it is an odd number because only odd numbers should be
displayed and accumulated to compute the sum.
With an if statement, we could check now if oddNum is true or false. If true, we
display the number and accumulate the sum. If false, we just proceed with the next
execution of the loop.
Declare sum at the declaration area.
Print ctrNum with a space concatenated with it to separate it for the next number to
be printed out.
Accumulate sum by adding the ctrNum to it.
Reaching the end brace of the loop, it will loop back and decrement ctrNum. Test
again the condition until it reaches 0. If it has not reach 0 yet, it will again implement the
statements within for loop.
As the for loop terminates, we need to print the sum of its number. The \n is needed
to move the cursor to the next line. Refer below as the final code of our program:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]Assessment 4:
CHECK THE ASSESSMENT MODULE
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]CHECK THE ASSESSMENT MODULE
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]The break Statement
The break statement change the flow of control in a program. As you have noticed,
a break statement, when executed in a switch/case statement, it terminates the case
statement. With this, we can use the break statement in while, do-while and for loops to
immediately exit from the loop. The break statement usually used for two purposes which
is to exit early from a loop and to skip the remainder of the switch/case statement.
Suppose that you’re going to design a program AverageNumber that computes
the average number of all the entries entered by the user. User enters -1 to end data entry
and proceed displaying the average:
Sample Input/Output:
Enter number [-1 to quit]: 1.5
Enter number [-1 to quit]: 3.5
Enter number [-1 to quit]: 5.0
Enter number [-1 to quit]: 6.8
Enter number [-1 to quit]: -1
Average number is 4.2
We start importing and declaring the Scanner class for our input object. Anticipate
that the numbers to be entered are with a decimal point. We use number as our variable
name in holding all the entries. Initialize it with value 0. This would be the beginning of our
program:
Let us use the while statement that will handle the indefinite entry of numbers. To
create that illusion of no definite end, we set the boolean expression inside the while
statement parentheses to true.
Inside the while body we place our prompt message together with the variable
number that will accept the numbers entered. Take note that we use nextDouble() method
is used for numbers with decimal numbers. We have our program at this point:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
The logic of the program is accumulate/add all the numbers that are not -1. Here
we need a variable that will do that. We use sum that will hold and add the values entered.
Create also variable divisor that will count all valid inputs. We insert next on the input the
if condition that will validate if number is not equal to -1. Inside the if condition, accumulate
number assign to sum and increment our divisor. Do not forget to declare our variables in
the declaration area.
What will happen if number is -1? Good question. We will set our else condition with
a statement break. Break here means is to escape the while loop.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
After that, outside the while loop, we print our average for the numbers. We simply
concatenate text "\nAverage number is " with the sum/divisor. Refer below as our final
program:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
The loop within a loop
Loop within a body of a looping statement are what we call nested loop. The use of nested
loops is printing a table with rows and columns. Sometimes, this simplifies the code
solution of a problem. Consider the following:
Design program SquareHash that displays the number of hashes in square figure
depending on the size entered by the user.
Sample Input/Output:
Enter size of hash: 3
###
###
###
How do we formulate a solution for this kind of problem? Let us observe few things:
1. The hash symbol prints with number of times on each row depending on
the value the user entered. On our example, if we entered 3 we generate 3 hashes
on each row.
2. The number of rows to be printed depends also on the size entered by the
user. So, it is the same with the number of hashes printed on each row. It is a 3 by
3 figure.
What would be the algorithm of the solution for this?
1. Accept the number size of the hash entered.
2. Set the starting value of rows to print.
3. Continue printing on each row as long as it is less than or equal to the
number of size of the hash entered.
3.1 Set the starting value of number of hash to print.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected] 3.2 Continue printing the hash symbol as long as number of hash to
print is less than or equal to the number of size of the hash entered.
3.2.1 Print hash symbol horizontally.
3.2.2 Increment the value of number of hash already printed.
3.3 Advance line to the next row.
3.4 Increment the value of row already printed.
You could refer to the flow chart below if you prefer to present the logic:
We are done presenting the flow of the program. Let us code this in Java.
Name our program SquareHash. Include the Scanner class to facilitate the
input entered by user. Display the input prompt that will the user to enter the size.
Assign the value of the entered on the prompt to variable hashSize. Do not
forget to declare hashSize as int on the declaration area. Set to 0 to as its initial
value.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
Follow the logic of the pseudo code or flow chart. Declare all the variables
on the declaration as you assign new variables in the program.
Our solution consist two looping statements. The outer loop uses the while
statement; inner loop (loop within the loop) uses for.
We use the statement System.out.print() to print the hash symbol
horizontally. System.out.println() to advance on the next line since the cursor stays
on the same line because of the System.out.print() command.
Adding 1 to numHash happens when the for statement loops back.
Incrementing 1 to row happens before we loop back to the while statement.
Refer to the final code for the problem:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected] Compile and test the program by entering different hash size values. Take a
look at the sample below.
The next example will help us to learn on reading programs that created by other
programmer. Refer to the code below:
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail: [email protected]
It would be helpful if we place looping scope boundaries/arrows to set where our
looping statement starts and where it ends. Refer to the figure below:
First, we declare variable x, y, and z. z has initial value set to 1.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected]Looping Section 1 starts here.
The program proceeds entering at do – while loop.
Looping Section 2 starts here.
Immediately, the loop executes assigning 3 to variable x.
Another looping statement is encountered. This time it is the while loop. The
while statement validates a boolean expression. Is x >= 1? The value of x at this
point is 3. 3 is greater than 1. The boolean expression is true. The program
implements the block statements within the while statement.
Looping Section 3 starts here.
Within the while block, there is another looping statement which is the for
loop. The for loop assigns an initial value of 1 to variable y. Validate the condition if
y < = x.
Is y <= x? y is 1 and x is 3. Therefore, the condition is true. Implement the
System.out.print (x + “ “). Print the current value of x (which is 3) and a space after
it.
As the for loops back, increment value of y. y now is 2.
Is y <= x? y is 2 and x is 3. True again. Print again the value of x (which is 3)
with a space after it.
Increment y as for loops back again. This time, y is now 3.
Is 3 <= 3 (as the condition validates again)? True. Print again the value of x
(3) with a space after it. We have our first row output below:
333
Increment y as for loops back. y now is 4.
Is y <= x? 4 <= 3? False. The program escapes from the for loop.
The cursor now proceeds on the next line with the System.out.println()
statement. Decrement the value of x. x now is 2.
Loop back on the while statement and validate again the boolean expression
x >= 1.
Is x >= 1? x is 2 so the condition is set to true.
Enter again within the while block statements. Assign 1 to y. Validate the
expression y <= x.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected] Is y <= x? 1 <= 2? The answer is true. Print the value of x (which is 2)
concatenated with a space.
Loop within the for statement. Increment y. y is now 2. Is 2 <= 2? True. Print
the value of x (still 2) with a space after it. Loop again the for statement. Increment
y. This time y is 3.
Is y = x? 3 <= 2? False. Exit the for loop block.
Output at this point is:
333
22
Cursor advance with the next line by statement System.out.println().
Decrement x. x is 1.
Loop back on while statement. Is x >= 1? x is 1 therefore, equal to 1. True.
Assign 1 once again to y as you enter the for loop statement. Is y <= x? True
again since y and x has a value of 1 each. Print value x joined by a space.
Loop for statement. Increment y. y is 2.
Is 2 <= 1? False. Escape once again the for loop statement.
Output now is:
333
22
1
Looping section 3 ends here.
Advance cursor one line by System.out.println(). Decrement x. x has value
0.
Loop back on while statement. Is x >= 1? False. 0 is not greater than or equal
to 1. Exit on the while loop.
Looping section 2 ends here.
Cursor advance another line as another System.out.println() is implemented.
Increment z. z is now 2.
Validate the do – while condition.
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected] Is z < 3? Is 2 < 3? True. Implement again where the section 1 starts and up
to Looping section 2 ends here. Its déjà vu once more.
Advance another line with System.out.println(). Add 1 to z. z now is 3.
Is z < 3? Is 3 < 3? False. They are equal.
Exit on do – while loop.
Looping section 1 ends here.
There is no more statement to do after the do – while loop. Program
terminates.
The final output of the program is:
333
22
1
333
22
1
Assessment 5:
1. Simulate the given programs then show the output:
CHECK THE ASSESSMENT MODULE
New Era University
College of Computer Studies
Rm. 247-B, High School Annex B, New Era University
Tel. No.: (+632) 981-4221 loc 3825
E-mail:
[email protected] c.
CHECK THE ASSESSMENT MODULE