You are on page 1of 15

Study Guide in FM-AA-CIA-15 Rev.

0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

Module No. 4
MODULE TITLE

REPETITION CONTROL STRUCTURES

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

At the end of the lesson, the student should be able to:


 Learn about the loop structure
 Create programs using while loop structure
 Create programs using do...while loop structure
 Create programs using for loop structure

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.

The while statement has the form,

while( boolean_expression )
{
statement1;
statement2;
. . .
}

The statements inside the while loop are executed as long as the boolean_expression evaluates
to true.

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

For example, given the code snippet,

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.

The following are other examples of while loops,


Example 1:
int x = 0;
while (x<10)
{
System.out.println(x); 
x++;
}

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”);

Example Program No. 1

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{

public static void main(String[] args){


BufferedReader reader = new BufferedReader(
new InputStreamReader ( System.in));

PANGASINAN STATE UNIVERSITY 6


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

String name = "";


int counter = 0;

//gets the users' name


try{
System.out.print("Enter name: ");
name = reader.readLine();
}catch(Exception e){
System.out.println("Invalid input");
System.exit(0);
}

//while loop that prints the name one hundred times

while(counter < 100){


System.out.println(name);
counter++;
}
}
}

Example Program No. 2

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
{

public static void main(String[] args){

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"));

//limits the exp to positive numbers only


if(exp < 0 ){
JOptionPane.showMessageDialog(null,
"Positive numbers only please");
System.exit(0);

PANGASINAN STATE UNIVERSITY 7


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

//while loop that solves for the power

while(counter < exp){


power = power*base;
counter++;
}

//displays the result

JOptionPane.showMessageDialog(null,base+" to the "+exp+" is "+power);

}
}

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.

The do-while statement has the form,

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.

Here are a few examples that uses the do-while loop:

Example 1:

int x = 10;
do
{
System.out.println(x);
x++;
}while (x<10);

This example will output 0123456789 on the screen.

PANGASINAN STATE UNIVERSITY 8


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

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); 

This example will output hello on the screen.

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.

Example Program No. 3

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
*/

public class HundredNames2


{
public static void main(String[] args){

BufferedReader reader = new BufferedReader(


new InputStreamReader( System.in));
String name = "";
int counter = 0;

PANGASINAN STATE UNIVERSITY 9


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

//gets the users' name


try{
System.out.print("Enter name: ");
name = reader.readLine();
}catch(Exception e){
System.out.println("Invalid input");
System.exit(0);
}

//do-while loop that prints the name one hundred times

do{
System.out.println(name);
counter++;
}while(counter < 100);
}
}

Example Program No. 4

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.
*/

public class Powers2


{

public static void main(String[] args){

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"));

//limits the exp to positive numbers only


if(exp < 0 ){
JOptionPane.showMessageDialog(null,

PANGASINAN STATE UNIVERSITY 10


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

"Positive numbers only please");


System.exit(0);
}

//do-while loop that solves the power given the base and
exponent

do{
if(exp != 0)
power = power*base;
counter++;
}while(counter < exp);

//displays the result

JOptionPane.showMessageDialog(null,base+" to the "+exp+" is


"+power);

}
}

for loop

The for loop, like the previous loops, allows execution of the same code a number of times.

The for loop has the form,

for (InitializationExpression; LoopCondition; StepExpression){


statement1;
statement2;
. . .
}

where,
InitializationExpression -initializes the loop variable.
LoopCondition - compares the loop variable to some limit value.
StepExpression - updates the loop variable.

A simple example of the for loop is,

for(int x=0; x < 10; x++ ){


System.out.println(x);
}

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.

PANGASINAN STATE UNIVERSITY 11


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

This example, is equivalent to the while loop shown below,

int i = 0;
while( i < 10 ){
System.out.print(i);
i++;
}

Example 1

import javax.swing.JOptionPane;

public class Sample1 {

public static void main(String args[]) {

int x=1;

for (int i=1; i<=3; i++) {


for (int n=5; n>=1; n--){
x=x+n;
}
}
JOptionPane.showMessageDialog(null,"Value of x = "+ x);
System.exit(0);
}
}

Example Program No. 5

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
*/

public class HundredNames3


{

public static void main(String[] args){

BufferedReader reader = new BufferedReader(


new InputStreamReader( System.in));
String name = "";

PANGASINAN STATE UNIVERSITY 12


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

//gets the users' name


try{
System.out.print("Enter name: ");
name = reader.readLine();
}catch(Exception e){
System.out.println("Invalid input");
System.exit(0);
}

//for loop that prints the name one hundred times

for(int counter = 0; counter < 100; counter++){


System.out.println(name);
}
}
}

Example Program No. 6

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.
*/

public class Powers3


{

public static void main(String[] args){

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"));

//limits the exp to positive numbers only


if(exp < 0 ){
JOptionPane.showMessageDialog(null,

PANGASINAN STATE UNIVERSITY 13


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

"Positive numbers only please");


System.exit(0);
}

//for loop for computing the power

for(counter = 0; counter < exp; counter++){


power = power*base;
}

//displays the result


JOptionPane.showMessageDialog(null,base+" to the "+exp+" is
"+power);
}
}

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);

PANGASINAN STATE UNIVERSITY 14


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

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

2. A loop that never ends is called a(n) ____ loop.


a. definite c. while
b. infinite d. for

3. Which of the following is true about a while loop?


a. The body of the loop is executed at least once.
b. The logical expression controlling the loop is evaluated before the loop is entered and after
the loop exists.
c. The body of the loop may not execute at all.
d. None of these

4. What is the output of the following Java code?


int num = 0;
while (num < 5)
{
System.out.print((5 - num) + " ");
num = num + 1;
}
System.out.println();

PANGASINAN STATE UNIVERSITY 15


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

a. 5 4 3 2 1 0 c. 4 3 2 1 0
b. 5 4 3 2 1 d. None of these

5. In a do...while loop, the loop will continue to execute until ____.


a. the loop control variable is true c. the user types EXIT
b. the loop control variable is false d. the program terminates

6. Which of the following is not a repetition structure in Java?


a. for c. while
b. switch d. None of these

7. What is the value of counter after the following statements execute?

counter = 1;
while (counter < 30)
counter = 2 * counter;

a. 16 c. 64
b. 32 d. 53

8. What is the output of the following Java code?


int num = 10;
while (num > 10){
num = num - 2;}
System.out.println(num);

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

10. What is the output of the folowing code?


int count;
int num = 2;

for (count = 1; count < 2; count++)


{
num = num + 3;
System.out.print(num + " ");
}
System.out.println();

a. 5 c. 2 5 8
b. 5 8 d. 5 8 11

PANGASINAN STATE UNIVERSITY 16


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

PANGASINAN STATE UNIVERSITY 17


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

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

PANGASINAN STATE UNIVERSITY 18


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

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.

4. Write a program that would display the number series below:

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

SALESMAN 1: (total number of salesman 1)


SALESMAN 2: (total number of salesman 2)
SALESMAN 3: (total number of salesman 3)
-------------------------------------
TOTAL: (total sales for the month)

SALESMAN WITH THE HIGHEST SALES: (salesman number)

REFERENCES

1. Farrel, Joyce, “Java Programming 9ed”, Course Technology, Cengage Learning


2. Cervantes, Julio, “Module in Java Programming”, Pangasinan State University.

PANGASINAN STATE UNIVERSITY 19

You might also like