COURSE - Problem Solving and
Programming Concepts (CSC3100)
TOPIC 6 – Problem Solving with Loop
Control
• Loop structure
• While, do-while and for loops
• Nested loops
• Input/output from file 1
Learning Outcomes
• At the end of this chapter, student should be
able to:
Use problem-solving chart to develop a solution using loop
structure. (C3, CTPS)
Construct program using while and do-while loop. (C3)
Use automatic counter and nested loop to develop problem
solution (C3, CTPS)
Construct program using automatic counter and nested loop.
(C3)
Distinguish the different uses of three types of loop structure.
(C4)
Use file to read/write input/ouput (C3)
2
Control Statements
• A basic mechanisms in a programming language that
control the order in which program statements are
executed.
• Three basic control statements used in programming:
1. Sequence statements
Performs a series of steps in a definitely sequence.
2. Selection/decision Statements
Make decision based on certain conditions
3. Repetition/loop Statements
Repeat a sequence structure under certain conditions
3
Motivation
• How to input name for 50 students?
• How to calculate total marks for 50 students?
• How to calculate total marks for more than one
students?
• ...
• And in many more problems that need us to process
more than once
how do we solve these problems?
4
Repetition (Loop) Logic
Structure
• Repeat structure
• To solve the problem that doing the same
task over and over for different sets of
data
• Types of loop:
– WHILE loop
– Do..WHILE loop
– Automatic-Counter Loop
5
While/WhileEnd
6
while Loop
• How to display a string Welcome to UPM 2
times?
Start
• Do the loop body if the condition is true.
count = 0
– Algorithm (Pseudocode):
False
• Set the count = 0 count <2
• While (count < 2)
Print “Welcome to UPM” True
Print
count = count + 1 “Welcome to
• WhileEnd UPM”
count = count + 1
End 7
while Loop
1. int count=0;
2. while (count < 2){
3. System.out.println(“Welcome to UPM”);
4. count = count+1;
5. } Stmt count Count< output
# 2
1 0
2 true
3 Welcome to UPM
4 1
2 true
3 Welcome to UPM
4 2
8
2 false
while Loop
• Example 1:
– To print the numbers from 1 to 100. Start
number = 1
– Algorithm (Pseudocode):
• Set the number = 1 false number
• While (number <= 100) <= 100
Print number true
number = number + 1 Print number
• WhileEnd
number = number + 1
End 9
while Loop
Start
• Example 2:
– Get the sum of 1, 2, 3, …, 5. Set number = 1
– Algorithm: Set total = 0
• Set the number = 1
False
• Set the total = 0 number <= 5
• While (number <= 5)
True
• total = total + number Display total
total =
• number = number + 1 total + number
• WhileEnd End
Number total
• Display total number =
1 0 number + 1
10
Examples
int b = 10;
while (b > 6) {
System.out.print(b + “ “); Loop body is executed, until
the condition becomes False
b--;
}
System.out.print(“End loop”);
int b = 10;
while (b < 6) {
System.out.print(b + “ “); Loop body is never executed,
b--; because the condition is
} always False
System.out.print(“End loop”);
11
Examples: Indefinite loop
Loop body is executed, and never stop, because the condition is
always True
int b = 10;
while (b > 6) {
System.out.print(b + “ “);
}
System.out.print(“End loop”); Loop variable is not updated
int b = 10;
while (b > 6) {
System.out.print(b + “ “);
Loop variable is incorrectly
b++;
updated
}
System.out.print(“End loop”);
12
Loop Control
Each loop must have:
1. Initial value int b = 10;
2. Control expression / end while (b > 6) {
value System.out.print(b + “ “);
3. Next value b--;
}
System.out.print(“End loop”);
13
Example 3: Average Mark
PAC
GivenData Required Results
5 marks averageMark
Processing Required Solution Alternatives
Use while loop to input 5 marks and calculate Define the mark
totalMark as input values.
Calculate totalMark
Calculate averageMark
IPO Input Processing Module Output
5 marks • Repeat 5 times: averageMark
• Read mark
• Calculate totalMark
= totalMark+mark
• End repeat
• Calculate averageMark =
totalMark/5 14
• Display averageMark
Example 3: Average Mark
• Pseudocode:
Start
Set totalMark= 0.0
Set count = 0
while (count < 5):
Read mark
totalMark = totalMark + mark
count = count + 1
averageMark=totalMark/5
Print averageMark
End
15
Example 3: Average Mark
• Java Program
Scanner input = new Scanner(System.in);
System.out.print(“Enter five marks: “);
int count = 0;
double total = 0.0;
double mark = 0.0;
while (count < 5) {
mark = input.nextDouble(); // Read mark
total += mark; // Add mark to total
count++;
}
double average = total/5;
System.out.print(“Average mark is ” + average);
16
Exercise: Average Mark
To calculate and print the average of five marks:
Start
1.Set totalMark= 0.0
2.Set count = 0
3.while (count < 5)
3.1 Read mark
3.2 count = count +1
4. totalMark = totalMark + mark
5. averageMark=totalMark/5
What is wrong with
6. Print averageMark this algorithm?
End
17
Examples using while Loops
1. Draw a flowchart that reads100 random integer
numbers.
2. Write a pseudocode that finds the smallest of 100
integer numbers.
3. Write a program that reads and calculates the sum of
an unspecified number of integers. The input 0 signifies
the end of the input.
18
Exercises
1. Write a while loop that prints the
numbers from 1 to 100.
2. Write a while loop to get the sum of 1 to
100 integer numbers ( 1+2+3+..+100)
19
do..while Loop
Statement(s)
(loop body)
true Loop
Continuation
do { Condition?
// Loop body; false
Statement(s);
} while (loop-continuation-condition);
20
do..while Loop
• Example 1:
– To print the numbers from 1 to 100.
(from while loop…)
– Algorithm (Pseudocode):
Start
• Set the number = 1
• While (number <= 100)
Print number
number = number + 1
• WhileEnd
End
21
do..while Loop
• The body of the loop will execute first
before checking the condition.
• Example:
Get the sum of 1, 2, 3, …100.
22
do..while Loop
Start
Set number = 1
Set total = 0
total = False
total + number
number = Display total
number + 1
True End
while
number <= 100
23
1. public class Sum1_100 {
2. public static void main(String[] args) {
3. int number = 1;
4. int sum = 0;
5. do {
7. sum = sum + number;
8. number++;
9. } while (number <= 100);
14. System.out.println(“The sum is “ + sum);
15. }
16. }
Number sum
1 0
24
Example 3: Average Mark
• Pseudocode:
Start
Set totalMark= 0.0
Set count = 0
do:
Read mark
totalMark = totalMark + mark
count = count + 1
while (count < 5)
averageMark=totalMark/5
Print averageMark
End 25
Example using do-while Loop
1. Draw a flowchart that reads100 random integer
numbers.
2. Write a pseudocode that finds the smallest of 100
integer numbers.
3. Write a program that reads and calculates the sum of
an unspecified number of integers. The input 0 signifies
the end of the input.
26
Example
int b = 10;
do {
System.out.print(b + “ “); Loop body is executed, until
the condition becomes False
b--;
} while (b > 6);
System.out.print(“End loop”);
27
Examples
int b = 10;
while (b < 6) { Remember this example?
System.out.print(b + “ “);
Loop body is never executed,
b--; because the condition is
} always False
System.out.print(“End loop”);
int b = 10;
do { In a do-while loop,
System.out.print(b + “ “);
loop body is executed once,
b--;
before the condition becomes
} while (b < 6);
False
System.out.print(“End loop”);
28
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) {
System.out.println
// loop body;
("Welcome to Java!");
Statement(s); }
}
29
for Loops
30
for Loops
• Example 2:
– Get the sum of 1, 2, 3, …, 5.
– Algorithm:
• Set the total = 0
for (number=1; number<=100; number=number+1)
•total = total + number
• Display total
Number total
1 0
31
Examples
for (int b = 10; b > 6; b--) {
System.out.print(b + “ “); Loop body is executed, until
} the condition becomes False
System.out.print(“End loop”);
for (int b = 10; b < 6; b--) {
System.out.print(b + “ “); Loop body is never executed,
} because the condition is
always False
System.out.print(“End loop”);
32
Automatic Counter Loop
• Use variable as a counter that starts counting at
a specified number and increment the variable
each time the loop is processed.
• The beginning value, the ending value and the
increment value may be constant. They should
not be changed during the processing of the
instruction in the loop.
33
Automatic-Counter Loop
A
C FALSE
Begin End
Step
TRUE
INSTRUCTION
INSTRUCTION
B
34
Automatic-Counter Loop
35
Example 3: Average Mark
36
Note
• The initial-action in a for loop can be a list of zero or more
comma-separated expressions.
• The action-after-each-iteration in a for loop can be a list of
zero or more comma-separated statements.
• Therefore, the following two for loops are correct.
• They are rarely used in practice, however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
} 37
Note
• If the loop-continuation-condition in a for loop is omitted,
it is implicitly true.
• Thus the statement given below in (A), which is an
infinite loop, is correct.
– Nevertheless, it is recommended that you use the equivalent
loop in (B) to avoid confusion:
for ( ; ; ) { Equivalent while (true) {
// Do something // Do something
} }
(a) (b)
38
Using for Loop
Problem:
Write a program that sums a series that starts with
0.01 and ends with 1.0. The numbers in the series will
increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and
so on.
39
1. public class ForLoopExample {
2. public static void main(String[] args) {
3. double i;
4. double sum = 0.0;
5. for {i = 0.01; i <= 1.0; i = i + 0.01)
6. {
7. sum = sum + i;
8. }
9. System.out.println(“The sum is “ + sum);
10. }
40
Examples using for Loops
1. Draw a flowchart that reads100 random integer
numbers.
2. Write a pseudocode that finds the smallest of 100
integer numbers.
3. Write a program that reads and calculates the sum of
an unspecified number of integers. The input 0 signifies
the end of the input.
41
Exercises
1. Write a while loop that prints odd numbers
from 1 to 10.
(Note: Odd number = 1, 3, 5, 7, 9, ....)
2. Rewrite the above code using a do-while loop.
3. Rewrite the above code using a for loop.
42
NESTED LOOP
43
NESTED LOOP
44
Example
for (int x = 1; x <= 5; x++){
int y = 10;
while (y >= 0) {
System.out.println (x + “\t” + y);
y -= 2;
}
System.out.println (“-----”);
}
System.out.println (“*****”);
Output?
45
Displaying the Multiplication
Table
Problem: Write a program that uses nested for loops
to print a multiplication table.
46
1. for (int i = 1; i <= 9; i++) {
2. System.out.print(“\n” + i);
3. for (int j = 1; j <= 9; j++) {
4. System.out.print (“\t” + (i*j));
5. }
6. }
47
Example using nested-loop
• Write a loop structure to read the number of
students in a class, and for each student, read
the marks for three subjects, and print the total
marks.
48
Example using nested-loop:
while in for
Scanner input = new Scanner(System.in);
System.out.print(“Enter the number of students: “);
int numOfStd = input.nextInt();
double mark = 0.0;
double total = 0.0;
for(int i = 1; i <= numOfStd; i++) {
System.out.println(“For student “ + i);
int subject = 1;
while (subject <= 3) {
System.out.print(“Enter mark for subject “ + subject + ": ");
mark = input.nextDouble(); // Read mark
total += mark;
subject++;
}
System.out.println(“Total marks for student “ + i + “ = ” + total);
}
49
Example using nested-loop:
for in for
Scanner input = new Scanner(System.in);
System.out.print(“Enter the number of students: “);
int numOfStd = input.nextInt();
double mark = 0.0;
double total = 0.0;
for (int i = 1; i <= numOfStd; i++) {
System.out.println(“For student “ + i);
for (int subject = 1; subject <= 3; subject++) {
System.out.print(“Enter mark for subject “ + subject + ": ");
mark = input.nextDouble(); // Read mark
total += mark;
}
System.out.println(“Total marks for student “ + i + “ = ” + total);
}
50
Which Loop to Use?
• The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (A) in the following figure
can always be converted into the following for loop in (B):
while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; )
// Loop body // Loop body
} }
(A) (B)
• A for loop in (A) in the following figure can generally be converted
into the following while loop in (B) except in certain special cases
(see Review Question 3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(A) (B)
51
Recommendations
• It is recommended that you use the one that is most
intuitive and comfortable for you.
• In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times.
• A while loop may be used if the number of repetitions is
not known, as in the case of reading the numbers until
the input is 0.
• A do-while loop can be used to replace a while loop if
the loop body has to be executed before testing the
continuation condition.
52
Caution
Adding a semicolon at the end of the for clause
before the loop body is a common mistake, as
shown below:
Logic
for (int i=0; i<10; i++); Error
{
System.out.println("i is " + i);
}
53
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
System.out.println("i is " + i);
i++;
}
However, in the case of the do-while loop, the following
semicolon is needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
} while (i<10); Correct
54
Problem Solving
You are asked to create a program that can display whether a student
passed or failed in a subject based on a student’s 4 test scores. The
program will calculate the average score of the test. If the average score is
below 50, the student fails and vice versa.
– Create IPO chart
– Draw a flow chart
– Write pseudocode -
– Write a program code
55
Input/output from file
• The File class is intended to provide an
abstraction that deals with most of the machine-
dependent complexities of files and path names
in a machine-independent fashion.
• The filename is a string.
• The File class is a wrapper class for the file
name and its directory path.
56
The File class
• Create File object
– Syntax:
java.io.File fileObject = new java.io.File(filename);
– Example:
java.io.File file = new java.io.File(“score.txt”);
• Check whether file already created or not
– Syntax:
file.exists()
– Example:
if (file.exists()) {
//statements
}
• Delete the file (will return true if the deletion succeed)
if (file.delete())
System.out.println(“File deleted”);
57
Text I/O
A File object encapsulates the properties of a file or
a path, but does not contain the methods for
reading/writing data from/to a file.
In order to perform I/O, you need to create objects
using appropriate Java I/O classes.
The objects contain the methods for reading/writing
data from/to a file.
This section introduces how to read/write strings and
numeric values from/to a text file using the Scanner
and PrintWriter classes.
58
Writing to a Text File
• Class PrintWriter is the preferred stream class for writing
to a text file.
• PrinterWriter has methods print, println, and printf.
• Create a stream to associate the output stream with the
file
java.io.File file = new java.io.File(“score.txt”);
PrintWriter output = new PrintWriter(file);
59
Writing Data Using PrintWriter
60
1. import java.io.*;
2. import java.util.*;
3. public class WriteDataToFile{
4. public static void main(String[] args) throws Exception{
5. String fname="phonebook.txt";
6. File file = new File(fname);
7. if(file.exists()){
8. System.out.println("File "+fname+" already exists");
9. System.exit(0);
10. }
11. // Create a file
12. PrintWriter output = new PrintWriter(file);
13. // Write formatted output to the file
14. output.printf("%-15s %-15s","Name","Phone Number");
15. output.println();
16. output.printf("%-15s %-15s","Ah Chong","012-2121669");
17. output.println();
18. output.printf("%-15s %-15s","Ahmad Jais","016-21634340");
19. output.close();
20. }
21. } 61
62
public class WriteData {
public static void main(String[] args) throws Exception
{
java.io.File file = new java.io.File("scores.txt");
if (file.exists()) {
System.out.println("File already exists");
System.exit(0);
}
java.io.PrintWriter output = new
java.io.PrintWriter(file);
output.print("John T Smith ");
output.println(90);
output.print("Eric K Jones ");
output.println(85);
output.close();
}
}
63
In file named score.txt, the contents are
John T Smith 90
Eric K Jones 85
64
Reading from a Text File
• Two common stream classes
– Scanner
– BufferedReader
• Scanner
– Replace the argument System.in with suitable stream
that is connected to the text file.
Scanner input = new Scanner (file);
Or
Scanner input = new Scanner (new
java.io.File(“scores.txt”));
65
Reading Data Using Scanner
66
1. import java.io.*;
2. import java.util.*;
3. import java.util.Scanner.*;
4. public class ReadData{
5. public static void main(String[] args) throws Exception{
6. String fname="phonebook.dat";
7. // Create a File instance
8. File file = new File(fname);
9. if(!file.exists()){
10. System.out.println("File "+fname+" not exists");
11. System.exit(0);
12. }
13. // Create a file
14. Scanner input=new Scanner(file);
15. input.useDelimiter(":");
16. // Read data from a file
17. String name = input.next();
18. String phone= input.next();
19. System.out.printf("%-15s %-15s",name,phone);
20. input.close();
21. }
22. }
67
68
Exercise
• Write a program that read student’s score from an input
file. This file contains student’s matric number, scores for
first test (20%), second test (20%), lab assignment (20%)
and final exam (40%). Your program need to find the total
scores for each student and grade based on the total
scores. Write in the output file the student matric number,
total score and grade.
69