CIS 1403 
Fundamentals of 
Programming
Lab 5: 
Iteration/Loops
1
Introduction
This lab aims to develop your knowledge and skills in apply various iteration/loop 
technique to solve programming problem.  The lab will cover the structure of for, 
while and do-while loops, provide examples on when to apply each.     Exceptions 
handling and reading from external text file is also covered with examples.
Skill-set
By completing this lab, the students will develop the following skills:
• Build accurate, simple and nested for, while and do while 
blocks of code
• Apply the concept of nested loop
• Use try and catch to handle exceptions
• Read data from an external text file
How to use this lab?
Follow the lab instruction in step by step and complete all exercises.  Watch 
the associated videos.   
Modify the examples to and exercises to experiment with different scenarios 
to solve a similar problem.
Click the QR code to access the videos and PowerPoint icon to access the 
associated PowerPoints.
Why do need iteration or loops in programming
When you need to repeat certain processes for number of times or until a 
condition is met, then you need to use loops. 
Java supports three types of loops that are:
for(int i=0; i<10;i++){
}
while(x<10){
}
do {
} while(x<10)
The for loop is used to repeat 
process for certain number of time.   
For example, repeat a process 10 
times.   You need to know the
number of times that the process is
needed.
The while loop is used to repeat a 
process based on a condition. 
For example, while the user is entering 
values more than 0, repeat the process.   
When he/she enters zero end the loop.  
Commonly used in reading data from 
database or a file.
The do - while loop is similar to the 
above while loop.   The only difference 
is that the condition is at the end.   It 
allows the process to start without any 
condition and at the end it check the 
condition, if the condition is met or 
true it goes and repeat the process.
Similar to nested if statements, you can add a loop inside another loop.  The inner 
loop must complete for the outer loop to move to the next step.   Throughout this 
lab we will practice number of examples for all types of loops.
3
The for loop
As discussed , the for loop is used to repeat process for certain number of time.   
Therefor, the for loop needs to use a counter to count the number of times.   When 
the counter is less than the specified number of times, the loop will be repeated.   
Every time the loop do the process, it needs to increase the counter.    The counter 
usually increased by 1.  However, there are situation when it needs to be increased 
by 2 or more.  We will see these examples later.   In many cases the variable i is used 
as the counter
In the example below, we have a for loop structure for repeating a process from i=0 
until i=9.   Please carefully examine structure:
for(int i=0; i<10;i++){
    //Process
}
1. Keyword 
for in lower 
case
2. The loop start 
with i = 0
3. The process is 
repeat while I < 10
4. The counter i is 
increased by one 
every time
Example one
5. These 
semicolons 
;
are 
important.
6. Opened curly 
brace
7. Closed curly 
brace
Here is a simple example that prints number from 0 to 9;  Output:
To skip one level every time, you can change i++ in line 2 to be i=i+2.
Make the above change and run the code.  
4
Modify the following code as per the instructions below for each change run the 
code and record your observation. 
Exercises
1. Change the loop to start from 1 instead of zero
2. Include 10 in the output
3. Print the numbers in descending order (from 10 to 1).
Example two
Write a Java code to allow the user to enter the price of 5 items, calculates and 
display the total and average.
• Line 6: We declared only one
variable for price. Without the
loop, we will need to declared 5
variables.
• Lines 10 to 14: The for loop that
start from 1 to 5 (5 is included)
• Line 11: displays a message to
the user to enter price
• Line 12: allows the user to enter
price
• Line 13 calculates the total.
Every time the loop goes on the
total is increment by the price
value of the item
• Line 15: calculates the average.
Please note the average is
calculated after the loop is
completed.
• Line 16 and 17: displays the
results
5
Example three
Assume that are man people are going to use the code in example two.   Each of 
these users has different number of items.   How can we change the code to allow 
each user to first enter the number of items then the price of each item.
We made some changes to the code:
Added a new int 
variable n to store 
number of items.
Replaced 5 in the 
loop with n
Added line 12 and 
13 to allow the 
user to enter a 
value for n.
Exercise
• Redesign/structure the above code using methods.
• Think of at least two more similar problems that you can solve using the code 
from the above example
• Discuss any limitation of the above code and how you can address 
6
Nested for loop
j
i
Let us imagine that you have two loops that are (i) and 
(j).   The loop (j) is inside the loop (i).   Loop (j) is called 
inner loop and the loop (i) is outer loop.
When you run such code, the outer loop (i) will start 
with the first value, then loop (j) will run from 
beginning to end. 
When loop (j) is completed it goes to the loop (i).  In this case the loop (i) will move to 
the next number and then the loop (j) will start again.   This will continue until the end 
of the loop (j).
Example four
The example below contains two loops.  The loop (i) runs from 1 to 5 and the loop (j) 
runs from 1 to 3.   The loop (j) is inside (i).   Every time the loop (j) run, the code display 
the value of i and j.    Examine the code carefully and follow the illustration.
The loop (i) start with the value 1.  Then, it 
goes to the loop (j), which start by one.   The 
output will be I = 1 and j = 1.
The loop (j) will move to the next value 
which j = 2.  The loop (i) is still at value of i 
=1.  The output will be i = 1 and j =2.
The loop (j) will move to the next value 
which j = 3.  The loop (i) is still at value of i 
=1.  The output will be i = 1 and j =3.
The loop (j) has reached the end and it go 
back to the loop (i)
The loop (i) will move to the next value, 
which i = 1.  The loop (j) will start by j=1.  
The output will be i = 2 and j=1.
This will continue until the end of the loop (i)7
The while loop
The while loop starts the loop only when the 
condition is met.  It is commonly used in 
reading data from a database or an external file.   
As long as the condition is still true, the loop 
will continue.     
As you can see from the flow –chart on the 
right, only when the condition is true, the loop 
will start.  When the last line in the body of the 
loop is executed, the control goes back to the 
condition of the loop.  If the result of the 
condition is false, the execution skip the body 
of the loop and the code continue to the rest of 
the program.
Start
Process
Is 
condition 
true?
Body/
Process
Stop
true
false
Example six
In This example, we will write a Java code that allows the user to enter price of 
items one by one.  To end the program, the user need to enter 0.   When 0 is 
entered, the number of items, total, and average are displayed on the screen.
• Line 11 and 12 allows the user to
enter the price of an item.
• If the user enter a value more
than zero, the loop will start
• Increase number of items
by 1 (line 15)
• Add price to the total
(line16)
• Request the user to enter
the price of the second
item (lines 17 and 18)
• If the user enters price
more than zero, the lines
from 15 to 18 are
executed, otherwise, the
program move to line 21
8
The do-while loop
Start
Process
Is 
condition 
true?
Body/
Process
Stop
true
false
The do while loop is similar to the while loop.   
The only difference is that in do while the 
condition is at the end.
Here is the same example, but with do while 
instead of while.
• The loop start from line 12 and ends in line 17.
• Please note that you need a semicolon at the end of the condition (line 17).
• The two lines that ask the user to enter value for price before the start of the loop in case of
the previous example (using only while) has been removed. See the previous page.
• Line 19 is added to ensure correct number of items. The do while loop will increment n even
when the user enter 0 for price.
• When the loop start the following will happen
• Increase number of items by 1 (line 13)
• Allow the user enter the price (lines 14 and 5)
• Add price to the total (line16)
• Check if the value is entered more than 0 (line 17). If true, go back to line 13. Else go
to line 19.
9
Catching the user errors
To avoid terminating the program when user enter the wrong information or when a 
process can not be perform most programming language has a mechanism for 
catching these errors and displaying a message to the user inform him/her of the 
error.    This process is referred to as exceptions.
Some of these errors including:
• Enter incorrect data type.   For example, the program requires entering a double 
value and instead the user entered a text
• Can not access files or data
• Dividing by zero is a common error
In this link you will find 12 widely used built-in Java exceptions with examples.
Here is the while loop examples with exception.
• The code from line 12 to 21 are
put inside a try block. The
reason for this is that we are
expecting some user by mistake
will enter a text or other
characters instead of price. Line
13, 16, 26 may cause this error.
Therefore, they are included in
the try block with other codes.
• Lines 22 to 24 will be executed
when such error occur.
• Line 23 display the message to
the user.
In addition to try catch, there is also try finally.   The only difference that the code in 
finally will be executed even when the error did not occur.
10
Reading data from an external file
Nowadays, most of the data that we work with are available in external files and in 
various format such as text, excel, CSV, database, etc.  Therefore, no need to enter 
this information again using keyboard specially when the files are too long.   For 
example, a supermarket with thousands of sales records.
Using while few more Java packages we can perform this task.   
Example seven
Assume we have a text file with the name “supermarket.txt” which includes the 
price of all sales products in the supermarket.  
Here is the code with explanation: Importing the File class that 
helps with reading an 
external files.
Importing a special file 
exception
This line creates an file 
object using the file name
This is our usual Scanner 
object.   The only difference 
that we are using file instead 
of System.in. The variable 
file is the same one in line 9.
The condition in the while 
loop can be read as 
”continue the loop while
there is a next line” or 
”continue the loop while
not at the end of the file.”
Lines 16 to 18 are not new.
Lines line 21 uses the 
Scanner object to close the 
file.
Lines 23 to 25 are executed 
when the program can not 
find the file.
11
1. Develop a program that outputs the integers from 2 to 14.
2. Develop a program to calculate the sum of all decimal integers from 20 to 
30.
3. Develop a program to add all even numbers from 10 to 20.
4. Develop a program that will display the first 10 integers (0 t o 9), with their 
squares and cubes (the cube of 2 is 23 which is equal to 2*2*2 or 8).
5. Develop a program that outputs the integers from 10 to 1.
6. Develop a program that outputs the integers from 1 to 10 except 5.
7. Develop a program that will output the multiplication table for 7 as shown 
below:
1 x 7 = 7
2 x 7 = 14
….
11 x 7 = 77
12 x 7 = 84
 
8. Develop a program that will output the multiplication table for 7 and 8 as 
shown below:
1 x 7 = 7 1 x 8 = 8
2 x 7 = 14 2 x 8 = 16
3 x 7 = 21 3 x 8 = 24
…. …
10 x 7 = 70 10 x 8 = 80
11 x 7 = 77 11 x 8 = 88
12 x 7 = 84 12 x 8 = 96
 
9. Develop a program that reads temperatures for a week from a user and 
displays the average of the temperatures.
10. Assume that a car consumes 10 gallons of fuel every 400km. Also assume 
that the cost of a gallon of fuel is 6.25 AED. Write a program to ask the user 
to enter the length of daily trips over a 7-day week and calculate and 
display the total week’s cost.
Hint: number of gallons consumed per trip = tripLength * 1 / 40
11. Salem bought a new Rahal card that has been credited with 300 AED. Write 
a program to ask Salem to enter each day’s fuel cost for a whole week and 
calculate and display the total week’s cost and the amount of credit left in 
the card.
Exercises
12
12. Improve the program in problem 11 so that if the fuel’s price is more than the 
remaining balance, the program displays a message to the user saying “Not enough 
credit. You current credit is ….”
13. Improve problem 12 so that the user can not enter invalid price.
14. A section has 10 students. Write a program to ask the teacher to enter 3 test marks 
between 0 and 100 for each student and calculate and display the average mark 
alongside an appropriate message. Valid marks are from 0 to 100.
Average Mark Message
average < 60 Failed
60 <= average < 75 Good Mark
75 <= average < 90 Very Good Mark
90 <= average <= 100 Excellent Mark
13

Cis 1403 lab5_loops