Control Structure
ESSON Loop and Jump Statements
Course Learning Outcomes: Intended Learning Outcomes:
- Explain and execute the
fundamentals, structure, and Differentiate loops/iteration based on functionality.
syntax of object-oriented Use appropriate loops/iteration structures based on given
programming. problem.
- test, verify, and debug object-
Understand how branching statements affects program flow.
oriented programs.
Skills Competencies:
Use loop control structure to
solve a given problem
Topics:
Introduction to Loops
Pre-Conditional Loop (for and while stmt)
Post-Conditional Loop (do-while stmt)
Jump Statements (break and continue)
What is Loop Statement?
- Loops are used to execute a set of program statements repeatedly until a particular condition
is satisfied.
- A loop statement allows us to execute a statement or group of statements multiple times until
the condition set is false.
- Types of Loop Statement
o Counter-Controlled Loop (for loop).
o Sentinel-Controlled Loop (while loop).
o Result-Driven Loop (do-while loop).
for - a pre-conditional loop.
loop - use when the number of iteration is known.
- a pre-conditional loop.
while - use when the number of iteration is NOT known.
loop
- iteration is based on a sentinel value or flag or most of the times it is
dependent on the user answer. (i.e. Want to try again [y/n] ?)
do-while - a post-conditional loop. The condition is set at the bottom of the loop.
loop - loop statement/s is executed at least once.
- iteration is based on the result value inside the loop statement.
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Counter-Controlled Loop – The for statement
initialization
- a pre-conditional loop. (the conditional is checked first.)
- Use when the number of iteration is known. Increment /
decrement
Syntax: stmt2;
for (initialization ; condition; step-size){ TRUE Loop
condition
stmt1; statements
stmt2; FALSE
stmtn;
} Program
statements;
Initialization : sets a variable before the loop starts. It is the initial value to start the count of
iteration. This statement is only executed once.
Condition : a Boolean condition set to check if the loop statement will be executed or not.
If the condition is true the loop statement is executed, otherwise the loop
statement is skipped. The condition is evaluated in each iteration.
Step-size : after every the loop body execution, the step-size is performed. Step-size can
either be an increment or a decrement statement. The step-size is responsible
on the update of the loop counter.
Example: [Link]
1 public class forStmt {
2 public static void main(String[] args){
3
4 for (int ctr=1; ctr<=10; ctr++) {
5 [Link](ctr + “\t”);
6 } //end of for
7 [Link](“\n Thank You.”);
8 } //end of main
9 } //end of class
Output:
1 2 3 4 5 6 7 8 9 10
Thank You.
Let’s take a look at line 4.
4 for (int ctr=1; ctr<=10; ctr++) {
int ctr=1; is the initial statement which indicates that the counting of the loop starts at 1.
ctr<=10; is the conditional statement that is evaluated in each loop. The loop continues until the
condition is evaluated as false.
ctr++ is the step-size indicating an increment of ctr for each loop.
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Example: [Link]
1 public class forStmt2 {
2 public static void main(String[] args){
3
4 for (int i=5; i<=50; i+=5) {
5 [Link](i + “\t”);
6 } //end of for
7 [Link](“\n This is an increment of 5.”);
8 } //end of main
9 } //end of class
Output:
5 10 15 20 25 30 35 40 45 50
This is an increment of 5.
4 for (int i=5; i<=50; i+=5) {
Checking line 4, notice the initialization statement i=5. This is the reason why the output starts printing 5.
Notice also the step-size, i+=5 (i.e. i=i+5), this indicates an increment of 5 for each iteration. Lastly the
condition i<=50 indicates that the loop stops when the value of i is greater than or equal to 50.
Example: [Link]
1 public class forStmt3 {
2 public static void main(String[] args){
3
4 for (int j=10; j>=1; j--) {
5 [Link](j + “\t”);
6 } //end of for
7 [Link](“\n This is an Example of decrement step-size.”);
8 } //end of main
9 } //end of class
Output:
10 9 8 7 6 5 4 3 2 1
This is an Example of decrement step-size.
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Sentinel-Controlled Loop – The while statement
- a pre-conditional loop.
- use when the number of iteration is NOT known.
- iteration is based on a sentinel value or flag or most of the times it is dependent on the user
answer. (i.e. Want to try again [y/n] ?)
Syntax: initialization
initialization;
while (condition) { Sentinel
statement
while body;
sentinel statement; TRUE Loop
} condition
statements
FALSE
Program
statements;
Example: [Link]
1 import [Link];
2 public class WhileStmt {
3 public static void main(String[] args){
4 Scanner UserInput = new Scanner([Link]);
5 char ans=’y’;
6
7 while (ans==’y’) {
8 [Link](“What a Game.”);
9 [Link](“Want to play again? [y/n]”);
10 ans = [Link](0);
11 } //end of for
12 [Link](“This is a while statement”);
13 } //end of main
14 } //end of class
Output:
What a Game.
Want to play again? [y/n] y
What a Game.
Want to play again? [y/n] y
What a Game.
Want to play again? [y/n] n
This is a while statemet
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Rewriting a for statement using while statement
Problem:
Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!.
For example:
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
Write a program that will display the factorial of a given integer number.
Solution: [Link]
1 import [Link];
2
3 public class FactorialUsingFor {
4 public static void main(String[] args){
5
6 Scanner Input = new Scanner([Link]);
7 int factorial=1,num;
8
9 [Link](“Enter an integer to be factored.”);
10 num = [Link]();
11
12 for (int a=1; a<=num; a++) {
13 factorial *= a; //this can be written as factorial = factorial*a;
14 } //end for
15
16 [Link](“FactoriaL of ” + num + “ is ” + factorial);
17 } //end of main
18 }//end of class
Output:
Enter an integer to be factored. 5
Factorial of 5 is 120
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Now, let us re-write the program [Link] using the while statement.
Here, we will just rewrite lines 12 to 14 using the while statement.
12 for (int a=1; a<=num; a++) {
13 factorial *= a; //this can be written as factorial = factorial*a;
14 }
Solution: [Link]
1 import [Link];
2
3 public class FactorialUsingWhile {
4 public static void main(String[] args){
5
6 Scanner Input = new Scanner([Link]);
7 int factorial=1,num;
8
9 [Link](“Enter an integer to be factored.”);
10 num = [Link]();
11
12 int a=1;
13 while (a<=num) {
14 factorial *= a; //this can be written as factorial = factorial*a;
15 a++;
16 } //end for
17
18 [Link](“FactoriaL of ” + num + “ is ” + factorial);
19 } //end of main
20 }//end of class
Output:
Enter an integer to be factored. 5
Factorial of 5 is 120
The comparison: initialization
conditiion
for (int a=1; a<=num; a++) { int a=1;
factorial *= a; while (a<=num) {
}
factorial *= a; step-size factorial *= a;
a++;
}
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Result-Driven Controlled Loop – The do-while statement
- A post-conditional loop. Meaning, the condition of the loop is found at the bottom does the
body of the loop is always executed at least once.
- Is used when the number of iteration is not known.
- is called an exit control loop. Unlike for and while statement, the do-while statement
checks condition at the end of the loop.
- The do-while statement is used if the condition set depends on the result processed inside its
loop body.
- Example: a program that continuously check if the password entered in correct. So the result
of the comparison between the entered password and the stored password is checked
continuously until it matches.
Syntax: Loop
statements
do { TRUE
loop body;
result
statement condition
} while (condition);
FALSE
Program
statements;
Example: A program that does not accept a negative input value.
Filename: [Link]
1 import [Link];
2 public class DoWhileStmt {
3 public static void main(String[] args){
4 Scanner Input = new Scanner([Link]);
5 int num;
6
7 do {
8 [Link](“Enter an integer:”);
9 num = [Link]();
10 } while (num<0); //the condition depends on the input value.
11
12 [Link](“Number entered is ” + num );
13 }//end of main
14 }//end of class
Output:
Enter an integer: -2
Enter an integer: -61
Enter an integer: 8
Number entered is 8
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Rewriting Loop Statements
Rules:
- All for statement can be expressed using while and do-while statement. However NOT all
while and do-while statement can be expressed using for statement.
- All while statement can be expressed using do-while statement. However NOT all do-
while statement can be expressed using while statement.
Example: Printing numbers by twos (2’s).
Filename: [Link]
1 public class UsingFor {
2 public static void main(String[] args){
3
4 for (int cnt=2; cnt<=10; cnt+=2) {
5 [Link](cnt + “\t”);
6 } //end of for
7 }//end of main
8 }//end of class
Filename: [Link]
1 public class UsingWhile {
2 public static void main(String[] args){
3 int cnt=2;
4 while (cnt<=10) {
5 [Link](cnt + “\t”);
cnt+=2;
6 } //end of while
7 }//end of main
8 }//end of class
Filename: [Link]
1 public class UsingDoWhile {
2 public static void main(String[] args){
3 int cnt=2;
4 do {
5 [Link](cnt + “\t”);
6 cnt+=2;
7 } while (cnt<=10);
8 }//end of main
9 }//end of class
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Using All Loop statements
Problem:
Create a program that will input four (4) periodical grades and compute for the average. The
program must NOT accept input grades greater than 100. The program must also allow user to
compute for another average if he wishes to.
Solution:
Ask for user to input 4 periodical grades (use for statement).
For each input grade, check if it is greater than 100. Keep asking if grade entered is greater
than 100. (use do-while statement).
Compute the average grade.
Display the computed grade.
Ask user if he will compute for another average. If so, repeat the entire program. (use while
statement).
Filename: [Link]
1 import [Link];
2 public class LoopDemo {
3 public static void main(String[] args){
4 Scanner Input = new Scanner([Link]);
5 int num, sum, average;
6 char ans=’y’;
7
8 while (ans==’y’) {
9 sum=0 ; average=0;
10 for (int cnt=1; cnt<=4; cnt++) {
11 do {
12 [Link](“Enter grade ” + cnt);
13 num = [Link]();
14 } while (num > 100);
15 sum += num; // equivalent to sum = sum + num
16 average = sum/4;
17 } //end of for
18 [Link](“The average grade is ” + average);
19
20 [Link](“Compute again? [y/n] ”);
21 ans = [Link](0);
22 }//end of while
23
24 }//end of main
25 }//end of class
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Code Dissection
Line 8: initialized the while statement, this statement will be check later if the user would like to compute
for another average.
Line 9: sum and average must be reset when another grade average is computed.
8 while (ans==’y’) {
9 sum=0 ; average=0;
Line 10: Loop 4 times to get the 4 periodical grade.
10 for (int cnt=1; cnt<=4; cnt++) {
Lines
9 11- 14: Checks
sum=0 input grade if greater than 100. It will keep on asking the grade until the user input a
; average=0;
grade less than or equal to 100. This is inside a for statement, since each 4 grades entered
needs to be checked.
11 do {
12 [Link](“Enter grade ” + cnt);
13 num = [Link]();
14 } while (num > 100);
Line 15: Compute the sum of all grade inputs.
Line 16: Compute for the average of the 4 input grades.
15 sum += num; // equivalent to sum = sum + num
16 average = sum/4;
Line 18: Display the computed average.
18 [Link](“The average grade is ” + average);
Line 20: Prompt the user if he will compute for another grade average.
Line 21: Reads the user input answer. The inputted answer here will determine the result of the condition
set on Line 8 : while (ans==’y’).if the user input ‘y’, the program will execute again the body
of the while statements (Lines 9 – 21). If the user input ‘n’, the program will skipped Line 9-21 and
proceed to Line 23 which terminates the program.
20 [Link](“Compute again? [y/n] ”);
21 ans = [Link](0);
22 }//end of while
23
24 }//end of main
25 }//end of class
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Self-Assessment
A. Instructions: Read and analyze the given questions carefully. Choose the correct letter that best
answer the question given. Write your answer on the space provided before the item number.
_____ 1. What are the three general types of loop structures?
a. counting loop, sentinel-controlled loop and result-controlled loop
b. infinite loop, counting loop, nested loop
c. while loop, for loop , do loop
d. count up loop, count down loop, infinite loop
_____ [Link] loop structure can be built using the while statement and do-while statement?
a. counting loops
b. sentinel-controlled loops
c. result-controlled loops
d. all of the above.
_____ 3. Which of the following is most likely to use a counting loop?
a. Checking that each price in a list of items offered for sale is less than P125.00.
b. Asking the user at the end of a game if the user wants to play again.
c. Checking if a particular integer is even or odd.
d. Trying various letter substitution combinations until a message in a secret code can be read.
_____ 4. What type of loop is implemented with a do statement?
a. Top-driven loop
b. Bottom-driven loop
c. Off-by-one loop
d. All of the above
_____ 5. Which of the following is most like to use a sentinel loop?
a. Checking that each price in a list of items offered for sale is less than P125.00.
b. Asking the user at the end of a game if the user wants to play again.
c. Checking if a particular integer is even or odd.
d. Trying various letter substitution combinations until a message in a secret code can be read.
_____ 6. What fact about a do loop is responsible for many program bugs?
a. The do must be matched with a while.
b. The do is not a good choice for a counting loop.
c. The body of a do loop is always executed at least once.
d. Using a do loop sometimes shortens a program.
_____ 7. Which of the following is most like to use a result-controlled loop?
a. Checking that each price in a list of items offered for sale is less than P125.00.
b. Asking the user at the end of a game if the user wants to play again.
c. Checking if a particular integer is even or odd.
d. Trying various letter substitution combinations until a message in a secret code can be read.
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
_____ 8. Based on the given code, how many times will “Welcome to Java.” be printed?
int count=0;
while (count < 10) {
[Link](“Welcome to Java.”);
count++;
}
a. 0
b. 9
c. 10
d. 11
_____ 9. Which of the following code fragment will print “Hello Java” 5 times.
a. for (int cnt=0 ; cnt<=5; cnt++) {
[Link](“Hello Java.”);
}
b. for (int cnt=1 ; cnt<5; cnt++) {
[Link](“Hello Java.”);
}
c. for (int cnt=0 ; cnt<5; cnt++) {
[Link](“Hello Java.”);
}
d. for (int cnt=2 ; cnt<=5; cnt++) {
[Link](“Hello Java.”);
}
_____10. A for loop includes a _____, which increases or decreases through each step of the loop.
a. initialization
b. condition
c. step-size
d. decrement
B. Analyze the given code fragments below and determine what this code fragment write to the monitor.
If the code have no output for display just write “No Output”.
1. 2.
for (int j=0; j<5 ; j++) { for (int j=10; j>5 ; j--){
[Link] ( j + “\t” ); [Link]( j + “\t” );
} }
Output: Output:
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
3. 4.
int j=1;
for (int count=0; count<=20; count+=2){ while (j<10) {
[Link](count + “\t“); [Link]( j + “\t“);
} j = j% 3;
}
Output: Output:
5. 6.
int x=100; int count=0;
while (x > 10) { do {
[Link]( j + “ “); [Link](count + “ “);
x -= 10; count++;
}
} while (count<6);
Output: Output:
7. 8.
int count=10; int y = 0;
while(y < 5){
do { y++;
[Link](count + “\t“); for(int i=1; i < 4; i++){
count-= 2;
y += i;
} while (count<0); }
}
[Link](y);
Output: Output:
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
9. 10.
char checked=’n’; char answer=’n’;
while (checked==’y’){ do {
[Link] (“The value is” + checked); [Link] (“Answer is” + answer);
} } while (answer==’y’);
Output: Output:
C. Fill-in the missing statement needed in the program fragment to accomplish the desired output
indicated in the question below.
1. Program prints out integers 5 through and 2. Program prints out even integers
including 15 0 2 4 6 8 10.
for (int j=5;____________; j++) { for (int j=0; j<=10 ;____________) {
[Link](j + “ “); [Link](j + “ “);
} }
3. Program prints out integers 4. Program prints out double values
- 3 -2 -1 0.2 0.4 0.6 0.8 1.0
for ( __________; j<0 ; j++) { for (double j=2; j<=10; j+=2) {
[Link](j + “ “); [Link]( _______ + “ “);
} }
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
D. Rewriting Program Codes
1. Write a for loop statement that duplicates the given while statement below. Write your codes on the
space provided.
Using while statement Using for statement
int x= C;
while ( x < 500) {
[Link] (x);
x += 5;
}
2. Write a for loop statement that duplicates the given do while statement below. Write your codes
on the space provided.
Using do while statement Using for statement
int j=1;
do {
[Link](j);
j++;
} while (j <= 3);
3. Write a while loop statement that duplicates the given for statement below. Write your codes
on the space provided.
Using for statement Using while statement
for (int j=0; j< 10; j++) {
[Link](j);
}
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Laboratory Activities
Problem 1: [Link]
The Fibonacci series: 0, 1, 1, 2, 3, 4, 8, 13, 21, … begins with 0 anf 1 and
has the property that each subsequent Fibonacci number is the sum of the previous two Fibonacci
numbers. Write an application program that reads a nonnegative integer from an input dialog and
computes and prints the Fibonacci Series.
Sample Program Dialog:
Enter a Number : 40
Fibonacci Series: 0, 1, 2, 3, 5, 8, 13, 21, 34
Want to Input Another Number? [y/n]: y
Enter a Number : 100
Fibonacci Series: 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89
Want to Input Another Number? [y/n]: n
Thank you for using this program.
Problem 2: [Link]
Write a program that reads a set of integers, and then prints the sum of the even and odd
integers.
Sample Program Dialog:
How many will you input? 5
Enter number 1: 7
Enter number 2: 10
Enter number 3: 3
Enter number 4: 1
Enter number 5: 12
The sum of even numbers is 22
The sum of odd numbers is 11
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
Problem 3: [Link]
Write a program that finds the summation of every number from 1 to num. The number will
always be a positive integer greater than 0.
Sample Program Dialog:
Enter a number : 4
Output : 4 + 3 + 2 + 1 = 10
Try again? [y/n] y
Enter a number : -5
Error: Invalid Input
Enter a number : 6
Output: 6 + 5 + 4 + 3 + 2 + 1 = 21
Try again? [y/n] n
Thank you for using the program.
Problem 4: [Link]
Write a program that generates a random number (1-100) and asks the user to guess what the
number is. If the user's guess is higher than the random number, the program should display
"Too high, try again." If the user's guess is lower than the random number, the program should
display "Too low, try again." The user is given five tries to guess. After five tries the program will
declare “Game Over” and reveals the random number. The program will then ask the user if he
wants to play again. If the user wants to play again, the program repeats.
Sample Program Dialog:
A random number is generated.
You have 5 tries to guess the number.
What’s your Guess? 50
Clue: Higher. Try Again
What’s your Guess? 70
Clue: Lower. Try again
What’s your Guess? 60
Clue: Lower. Try again
What’s your Guess? 55
Clue: Lower. Try again
What’s your Guess? 53
Game Over!
The random number is 52
Want to play again? [y/n] y
A random number is generated.
You have 5 tries to guess the number.
What’s your Guess? 40
Clue: Higher. Try Again
What’s your Guess? 43
You got it Right!
Want to play again? [y/n] n
Thank you for using the program.
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT
References:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
USTP-IT214: Object Oriented Programming Prepared by: Jocel L. Garrido, MIT