Module 4
Module 4
0 03-June-2020
Module No. 4
MODULE TITLE
MODULE OVERVIEW
In the previous lesson, we have given examples of programs, wherein statements are executed
that allows us to select and execute specific blocks of code while skipping other sections. In this
section, we will be discussing repetion control structures, which allows us to execute specific
blocks of code a number of times..
LEARNING OBJECTIVES
LEARNING CONTENTS
Repetition/loop control structures are Java statements that allows us to execute specific blocks
of code a number of times. Within a looping strucure, a Boolean expression is evaluated. If it is
true, a block of statements called the loop body executes and the Boolean expression is evaluated
again. As long as the expression is true, the statements in the loop body continue to execute.
When the Boolean evaluation is false, the loops ends. One execution of any loop is called an
iteration. There are three types of repetition control structures, the while, do-while and for loops.
while loop
The while loop is a statement or block of statements that is repeated as long as some condition is
satisfied.
while( boolean_expression )
{
statement1;
statement2;
. . .
}
The statements inside the while loop are executed as long as the boolean_expression evaluates
to true.
int i = 4;
while ( i > 0 ){
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.
Example 2:
//infinite loop
while(true)
System.out.println(“hello”);
Example 3:
//no loops
// statement is not even executed
while (false)
System.out.println(“hello”);
Create a program that prints your name a hundred times using while loop.
import java.io.*;
/**
* A program that prints a given name one hundred times
* using while loop
*/
public class HundredNames1{
Make a program that will compute the power of a number given the base and exponent using
while loop.
import javax.swing.JOptionPane;
/**
* Computes the power of a number given the base and the exponent.
* The exponent is limited to positive numbers only.
*/
public class Powers1
{
int base = 0;
int exp = 0;
int power = 1;
int counter = 0;
//gets the user input for base and power using JOptionPane
base = Integer.parseInt(JOptionPane.showInputDialog("Base"));
exp =Integer.parseInt(JOptionPane.showInputDialog("Exponent"));
}
}
do-while loop
The do-while loop is similar to the while-loop. The statements inside a do-while loop are executed
several times as long as the condition is satisfied.
The main difference between a while and do-while loop is that, the statements inside a do-while
loop are executed at least once.
do{
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 statements inside the do-while
loop are executed again.
Example 1:
int x = 10;
do
{
System.out.println(x);
x++;
}while (x<10);
Example 2:
//infinite loop
do{
System.out.println(“hello”);
} while (true);
This example will result to an infinite loop, that prints hello on screen.
Example 3:
//one loop
// statement is executed once
do
System.out.println(“hello”);
while (false);
Coding Guidelines:
1. Common programming mistakes when using the do-while loop is forgetting to write the
semi-colon after the while expression.
do{
...
}while(boolean_expression) //WRONG->forgot semicolon ;
2. Just like in while loops, make sure that your do-while loops will terminate at some point.
Create a program that prints your name a hundred times using do-while loop.
import java.io.*;
/**
* A program that prints a given name one hundred times
* using do-while loop
*/
do{
System.out.println(name);
counter++;
}while(counter < 100);
}
}
Make a program that will compute the power of a number given the base and exponent using do-
while loop.
import javax.swing.JOptionPane;
/**
* Computes the power of a number given the base and the exponent.
* The exponent is limited to positive numbers only.
*/
int base = 0;
int exp = 0;
int power = 1;
int counter = 0;
//gets the user input for base and power using JOptionPane
base = Integer.parseInt(JOptionPane.showInputDialog("Base"));
exp
=Integer.parseInt(JOptionPane.showInputDialog("Exponent"));
//do-while loop that solves the power given the base and
exponent
do{
if(exp != 0)
power = power*base;
counter++;
}while(counter < exp);
}
}
for loop
The for loop, like the previous loops, allows execution of the same code a number of times.
where,
InitializationExpression -initializes the loop variable.
LoopCondition - compares the loop variable to some limit value.
StepExpression - updates the loop variable.
In this example, the statement i=0, first initializes our variable. After that, the condition
expression i<10 is evaluated. If this evaluates to true, then the statement inside the for loop is
executed. Next, the expression i++ is executed, and then the condition expression is again
evaluated. This goes on and on, until the condition expression evaluates to false.
int i = 0;
while( i < 10 ){
System.out.print(i);
i++;
}
Example 1
import javax.swing.JOptionPane;
int x=1;
Create a program that prints your name a hundred times using for loop.
import java.io.*;
/**
* A program that prints a given name one hundred times using for
loop
*/
Make a program that will compute the power of a number given the base and exponent using for
loop.
import javax.swing.JOptionPane;
/**
* Computes the power of a number given the base and the exponent.
* The exponent is limited to positive numbers only.
*/
int base = 0;
int exp = 0;
int power = 1;
int counter = 0;
//gets the user input for base and power using JOptionPane
base = Integer.parseInt(JOptionPane.showInputDialog("Base"));
exp =
Integer.parseInt(JOptionPane.showInputDialog("Exponent"));
LEARNING POINTS
A loop is a structure that allows repeated execution of a block of statements. Within and
looping structure, a Boolean expression is evaluated, and if it true, a block of statements
called the loop body executes; then the Boolean expression is evaluated again.
A for loop initializes, tests, and increments in one statement. There are three sections within
the parenthesis of a for loop that are separated by exactly two semicolons.
You can use a while loop to execute a body of statements continually while some condition
continues to be true. To correctly execute a while loop, you should initialize a loop control
variable, test in while statement and then alter the loop control variable in the loop body.
The do-while loop test a Boolean expression after one repetition has taken place, at the
bottom of the loop.
LEARNING ACTIVITIES
Skills Warmup
True or False. Write your answer in the space provided.
_______ 1. A loop is a control structure that causes certain statements to be executed over and over
until certain conditions are met.
_______ 2. The loop condition of a while loop is reevaluated before every iteration of the loop.
_______ 3. If the initial condition of any while loop is false it will still execute once.
_______ 4. If the while expression becomes false in the middle of the while loop body, the loop
terminates immediately.
_______ 5. The output of the Java code (Assume all variables are properly declared.)
num = 10;
while (num <= 32)
num = num + 5;
System.out.println(num);
is: 32
_______ 6. A counter-controlled loop is used when the exact number of data entries is known.
_______ 7. The output of the Java code (Assume all variables are properly declared.)
n = 2;
while (n <= 6)
{
n++;
System.out.print(n + " ");
}
System.out.println();
is: 3 4 5 6 7
_______ 8. The control statements in the for loop include the initial expression, logical expression, and
update expression.
_______ 9. As in the while loop, the body of the for loop eventually changes the logical expression to
false.
_______ 10. The do...while loop has an exit condition but no entry condition.
Multiple Choice: Encircle the letter that corresponds to the correct answer.
1. In ____ structures, the computer repeats particular statements a certain number of times
depending on some condition(s).
a. looping c. selection
b. branching d. sequence
a. 5 4 3 2 1 0 c. 4 3 2 1 0
b. 5 4 3 2 1 d. None of these
counter = 1;
while (counter < 30)
counter = 2 * counter;
a. 16 c. 64
b. 32 d. 53
a. 0 c. 10
b. 8 d. None of these
9. The ____ loop checks the value of the loop control variable at the bottom of the loop after one
repetition has occurred.
a. while c. for
b. do...while d. else
a. 5 c. 2 5 8
b. 5 8 d. 5 8 11
SKILLS WORKOUT
Show the Output. Display the output of each of the following programs.
1. Assign1.java
import javax.swing.JOptionPane;
public class Assign1{
public static void main(String args[])
{
int x=5;
for (int j=2; j<=4; j++){
for (int m=10; m>6; m--){
for (int c=1; c<=5; c++){
x=x+c;
}
}
}
JOptionPane.showMessageDialog(null,"Value of x = "+ x);
}
}
2. Assign2.java
import java.io.*;
public class Assign2 {
public static void main (String[] args){
int j = 1;
while ( j < 10 )
{
System.out.print( j + " " );
j = j + j%3;
}
System.exit(0);
}
}
Hands-on Activity
1. Write a program that would input 10 numbers and then output the highest number. Output the lowest
number as well.
2. Write an application that displays all even numbers from 2 to 100 inclusive, and that starts a new line
after every multiple of 20 (20, 40, 60, and 80).
3. Mucho Dinero has P20,000.00 in his savings account. Write a program that would enter a series of
numbers terminated by a 0 sentinel. A positive number would mean a deposit in his account and a
negative number would mean a withdrawal. For each numbered entered the outstanding balance
must be displayed. The program should also check whether the amount to be withdrawn has sufficient
funds. If there is not, the message “INSUFFICIENT FUNDS!” must be displayed.
1 1 2 3 5 8 13 21 34 . . . .
A pattern must be established in displaying the numbers. The program will ask the user how many
sequence he wants.
5. JMC Enterprises has only 3 salesmen and for the month of July 2011, these 3 salesmen made 15
sales transaction combined. Make a program to input the 15 sales amount and the salesman code
denoting the salesman who made the sales. Use code 1 for salesman1, code 2 for salesman 2 and code
3 for salesman 3. The program should validate the value of the sales amount (must be between 1000
and 99999) and salesman code (must be between 1 and 3). If invalid, display the message “INVALID
ENTRY!” and then accept another value to disregard the invalid entry. Output the total sales using the
format below:
JMC ENTERPRISES
TOTAL SALES FOR THE MONTH OF JULY
REFERENCES