Computer Programming II
CSC 202
Module 1 Lecture 4
LOOPS
Dr. Akputu Oryina Kingsley
2
Motivation
Suppose that you need to print a string (e.g.,
"Welcome to Java!") a hundred times. It
would be tedious to have to write the
following statement a hundred times:
[Link]("Welcome to Java!");
So, how do you solve this problem?
Dr. Akputu Oryina Kingsley
3
Opening Problem
Problem:
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
100
times
…
…
…
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
[Link]("Welcome to Java!");
Dr. Akputu Oryina Kingsley
4
Introducing the While Loop
int count = 0;
while (count < 100) {
[Link]("Welcome to Java");
count++;
}
Dr. Akputu Oryina Kingsley
5
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
[Link]("Welcome to Java!");
Statement(s);
count++;
} }
count = 0;
Loop
false false
Continuation (count < 100)?
Condition?
true true
Statement(s) [Link]("Welcome to Java!");
(loop body) count++;
(A) (B)
Dr. Akputu Oryina Kingsley
6
Trace while Loop
Initialize count
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
7
Trace while Loop, cont.
(count < 2) is true
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
8
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
9
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 1 now
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
10
Trace while Loop, cont.
(count < 2) is still true since count
int count = 0; is 1
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
11
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
12
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 2 now
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
13
Trace while Loop, cont.
(count < 2) is false since
int count = 0; count is 2 now
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley
14
Trace while Loop
The loop exits. Execute the next
int count = 0; statement after the loop.
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
Dr. Akputu Oryina Kingsley