Revision CSCI250 Chapter 4
Revision CSCI250 Chapter 4
4.1 Introduction
4.2 The while Loop
4.2.2 Loop Design Strategies
4.2.4 Controlling a Loop with a Sentinel Value
4.3 The do-while Loop
4.4 The for Loop
1
4.1 Introduction
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:
System.out.println("Welcome to Java!");
So, how do you solve this problem?
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times …
…
…
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
2
4.1 (Continued)
int count = 1;
while (count <= 100) {
System.out.println("Welcome to Java");
count++;
}
3
4.2 The while Loop
Syntax of the while loop:
while (loop-continuation-condition){
Statement(s); // loop-body
}
int count = 1; //count is the loop counter and count = 1 is the counter
initialization
while (count <= 100) { // count <= 100 is called the condition
System.out.println("Welcome to Java");
count++; // count++ is called the counter update
}
while (count <= 100){ Loop header
System.out.println("Welcome to Java");
count++;
Loop body
}
4
4.2 (Continued)
Logic of the while loop:
Repeat the body of the loop as long as the condition is true.
When the condition becomes false the loop will stop.
count = 1;
Loop
false false
Continuation (count <= 100)?
Condition?
true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;
(A) (B)
5
animation
6
animation
7
animation
8
animation
9
animation
10
animation
11
animation
12
animation
13
animation
14
Example 2
int sum = 0, i = 1;
while (i < 10) {
sum = sum + i;
i++;
}
System.out.println("sum is " + sum);
// The output is:
// sum is 45
Variable i is initially set to 1. i < 10 is true since 1 < 10. Hence the
program adds the value of i to sum (0 + 1 = 1) so sum now is 1.
Then i is incremented to 2, and 2 is added to the sum (1 + 2 = 3) so
sum now is 3. Then i is incremented to 3, 4, and up to 10 and each
time the value of i is added to sum. When i is 10, i < 10 is false, so
the loop exits. Therefore, the sum is 1 + 2 + 3 + ... + 9 = 45.
15
Example 2 (Continued)
int sum = 0, i = 1;
while (i < 10) {
sum = sum + i;
}
System.out.println("sum is " + sum);
// Infinite Loop
// No output
16
Example 3
i++;
}
A loop that prints all even numbers between 10 and 31 inclusive :
int i = 10;
while(i < 31) { // Note: < is used instead of <= since 31 is odd
if(i % 2 == 0)
System.out.print(i + " ");
i++; Output
}
10 12 14 16 18 20 22 24 26 28 30
17
Example 4
int i = 1;
while(i <= 20) {
System.out.print(i + " ");
i = i * 2;
}
Output
1 2 4 8 16
18
Caution
int i = 0; Logic Error int i = 0;
while (i < 10); while (i < 10){ } Empty block
{ {
System.out.println("i is " + i); Equivalent System.out.println("i is " + i);
i++; i++;
} }
If you add a semi column by mistake after the condition of the loop then this will
mean that the loop has an empty body. If the condition is true then the empty
statement will be executed. This will be an infinite loop hence it is a logic error.
The statements after the ; are considered to be outside the loop.
int i = 0;
int i = 0; while (i < 10) {
while (i < 10) System.out.println("i is " + i);
System.out.println("i is " + i); }
Equivalent
i++; i++;
If you forget the necessary { } for the loop body then only the first statement after
the header is considered to be part of the body. The next statements are
considered to be outside the loop.
19
Trace it yourself
What does each of the below 6 loops output?
int i = 1; int i = 1;
while(i <= 3) { while(i <= 3)
System.out.println(i); System.out.println(i);
i++; i++;
}
int i = 1; int i = 1;
while(i <= 3) { while(i <= 3)
i++; i++;
System.out.println(i); System.out.println(i);
}
20
4.2.2 Loop Design Strategies
Step 1: Identify the statements that need to be repeated.
Step 2: Wrap these statements in a loop like this:
while ( ) {
Statements;
}
Step 3: Decide how many times the loop should repeat by
initializing the loop counter and writing the appropriate
condition and the appropriate statements for controlling the loop.
Statement to declare and initialize the loop counter;
while (loop-continuation-condition) {
Statements;
Additional statements for controlling the loop;
}
21
4.2.4 Controlling a Loop with a Sentinel Value
Often the number of times a loop is executed is not predetermined.
You may use an input value to signify the end of the loop. Such a
value is known as a sentinel value.
22
Solution
import java.util.Scanner;
public class SentinelValue {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int data, sum = 0;
// Read an initial data
System.out.print( "Enter an int value (the program exits if the input is 0): ");
data = input.nextInt();
// Keep reading data until the input is 0
while (data != 0) { // The sentinel is 0
sum += data;
// Read the next data
System.out.print( "Enter an int value (the program exits if the input is 0):
");
data = input.nextInt();
}
System.out.println("The sum is " + sum);
}
}
23
Review: What is the output in each of the following loops?
24
4.3 The do-while Loop
A do-while loop is the same as a while loop except that it executes
the loop body first and then checks the loop continuation condition.
Statement(s)
(loop body)
true Loop
do { Continuation
Condition?
// Loop body; Don’t forget “;”
false
Statement(s);
} while (loop-continuation-condition);
25
Comparing the while and the do-while
Loops
Example 1
Using while Using do-while
int i = 1; int i = 1;
while (i <= 3) { do {
System.out.print(i + " "); System.out.print(i + " ");
i++; i++;
} } while (i <= 3);
Output: 1 2 3 Output: 1 2 3
In memory i contains 4 at the end of the loop In memory i contains 4 at the end of the loop
In this example both the while and the do while work exactly
in the same manner.
26
Comparing the while and the do-while
Loops
Example 2
Using while Using do-while
No output Output: 11
In memory i contains 11. In memory i contains 12.
The loop does not work. The loop works once.
28
Exercise 4.8 (page 168): Write a program that prompts the user to enter the number
of students and each student’s score, and finally displays the highest score.
import java.util.*; Counter Controlled Loop
public class Exercise04_08 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numOfStudents = input.nextInt();
double highest = 0;
int i = 1;
do{
System.out.print("Enter a student score: ");
double score = input.nextDouble();
if (score > highest)
highest = score;
i++;
} while(i <= numOfStudents);
System.out.println("The highest score is " + highest);
}
}
29
4.4 The for Loop
for (Initial-Action; condition; Action-After-Each-Iteration) {
Statement(s); // loop body;
}
int i;
for (i = 1; i <= 100; i++)
System.out.println("Welcome to Java!");
Initial-Action i=1
The Action-After-Each-
Iteration is the Loop
false false
counter update. Continuation (i <= 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");
Action-After-Each-Iteration i++
(A) (B)
30
Order of execution in the for Loop
4. The counter update will be
1. The counter initialization executed last (after the body of
2. The condition will be
will be executed first. the loop).
executed second.
It will executed only once.
int i = 1;
while(i <= 100) { 3. The loop body will
be executed third (after
System.out.println("Welcome to Java!"); the condition).
i++;
} 4. The counter update will be executed last.
31
Different Formats of the for loop
Format 1 (Most commonly used format):
for (int i = 1; i <= 100; i++)
System.out.println("Welcome to Java!");
The loop counter i is declared inside the loop header. In this case i cannot be
only inside the loop. If we try to use it after the loop we get a syntax error.
Format 2:
int i;
for (i = 1; i <= 100; i++)
System.out.println("Welcome to Java!");
The loop counter i is declared before the loop header. In this case i can be used
inside and also after the loop.
32
animation
33
animation
34
animation
35
animation
36
animation
37
animation
38
animation
39
animation
40
animation
41
animation
42
Notes
We can have 1, 2, or more counters in the for loop separated by commas.
Similarly, when updating the counters we separate them with commas.
int j=0;
for(int i=0,j=0; i+j<10; i++, j++){ for(int i=0; i+j<10; i++){
// Do something Equivalent // Do something
} j++;
}
(a) (b)
Both parts (a) and (c) are correct and equivalent to (b). However, (a)
and (c) are hard to understand. Better to write (b).
for (int i=1;i<=100; ){ Equivalent for (int i=1;i<=100;i++){ Equivalent for (int i=1;i<=100; S.O.P(i++)){
S.O.P(i++); S.O.P(i);
} } }
43
Infinite for loop
If the 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 better to use the equivalent loop in (b) to avoid
confusion:
for ( ; ; ) { Equivalent while (true) {
// Do something // Do something
} }
(a) (b)
44
Caution
Adding a semicolon at the end of the for header (before the loop
body) is a common mistake, as shown below:
for (int i = 0; i < 10; i++); Logic Error: The loop ends at ;
System.out.println("i is " + i);
Hence the SOP statement is outside the loop.
Syntax error: When i is defined inside a
loop, it cannot be used after it.
Similarly, the following while loop has a logic error which will cause an infinite loop:
int i = 0;
while (i < 10); Logic Error
{
System.out.println("i is " + i);
i++;
}
In the case of the do 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
45