0% found this document useful (0 votes)
16 views45 pages

Revision CSCI250 Chapter 4

Chapter 4 discusses loops in programming, focusing on the while, do-while, and for loops, including their syntax, logic, and examples. It highlights the importance of controlling loops with conditions and sentinel values to prevent infinite loops. Additionally, it provides strategies for designing loops effectively and compares the behavior of different loop types.

Uploaded by

shehabhasan393
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views45 pages

Revision CSCI250 Chapter 4

Chapter 4 discusses loops in programming, focusing on the while, do-while, and for loops, including their syntax, logic, and examples. It highlights the importance of controlling loops with conditions and sentinel values to prevent infinite loops. Additionally, it provides strategies for designing loops effectively and compares the behavior of different loop types.

Uploaded by

shehabhasan393
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Review of Chapter 4 Loops

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)

The solution is to include the output statement inside a


repetition statement also known as a loop as in the example
below. The loop below is called the while loop. It will
repeat the output statement 100 times.

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

Trace while Loop


Initialize count
int count = 1;
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

6
animation

Trace while Loop, cont.


(count <= 2) is true
int count = 1;
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

7
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 1;
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

8
animation

Trace while Loop, cont.


Increase count by 1
int count = 1; count is 2 now
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

9
animation

Trace while Loop, cont.


(count <= 2) is still true since count
int count = 1; is 2
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

10
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 1;
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

11
animation

Trace while Loop, cont.


Increase count by 1
int count = 1; count is 3 now
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

12
animation

Trace while Loop, cont.


(count <= 2) is false since count is
int count = 1; 3 now
while (count <= 2) {
System.out.println("Welcome to Java!");
count++;
}

13
animation

Trace while Loop


The loop exits. Execute the next
int count = 1; statement after the loop.

while (count <= 2) {


System.out.println("Welcome to Java!");
count++;
}

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)

// What happens if the loop is mistakenly written as follows?

int sum = 0, i = 1;
while (i < 10) {
sum = sum + i;
}
System.out.println("sum is " + sum);
// Infinite Loop
// No output

Notice we skipped the statement i++; which is the counter update.


As a result the loop will never stop because i is always 1 and i < 10
will always be true. This loop is called an infinite loop.
Therefore make sure that the loop condition eventually becomes
false so that the loop will terminate.

16
Example 3

A loop that prints all numbers between 10 and 31 inclusive :


int i = 10;
while(i <= 31) { Output
System.out.print(i + " "); 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

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

In the previous example we used the addition operator + to update the


loop counter. We can use any numeric operator to update the counter
such as +, -, *, or /.

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);
}

int i = 3; int i = 10;


while(i >= 1) { while(i <= 3) {
System.out.println(i); System.out.println(i);
i--; 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.

Write a program that reads and calculates the sum of an unspecified


number of integers. The input 0 signifies the end of the input.

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?

In the below S.O.P means System.out.println.


(a) (c) (e)
int i = 0; int x = 3; int i = 0, x = 0;
while (i < 3) { int i = 0; while (i < 0);
while (i < 3) { x += 1;
S.O.P("hi");
x += 1; i += 1;
i++; i += 1; S.O.P(x);
} }
S.O.P("bye"); S.O.P(x);

(b) (d) (f)


int i = 0; int i = 0;
int i = 0; while (i < 0)
while (i < 0)
while (i < 3) S.O.P("hi");
S.O.P("hi");
i++; S.O.P("Bye");
S.O.P("hi");
S.O.P("bye");

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

int i = 11; int i = 11;


while (i <= 3) { do {
System.out.print(i + " "); System.out.print(i + " ");
i++; i++;
} } while (i <= 3);

No output Output: 11
In memory i contains 11. In memory i contains 12.
The loop does not work. The loop works once.

Since in the do-while loop the condition is checked at the end


the do while is guaranteed to work at least once.
27
Example: Write a program that reads and calculates the sum of an unspecified
number of integers. The input 0 signifies the end of the input.

import java.util.*; Sentinel Controlled Loop


public class TestDoWhile {
public static void main(String[] args) {
int data;
int sum = 0;
Scanner input = new Scanner(System.in);
do {
System.out.print("Enter an integer (the input ends if it is 0): ");
data = input.nextInt();
sum += data;
} while (data != 0);
System.out.println("The sum is " + sum);
}
}

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!");

The Initial-Action is the


counter initialization.

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.

for (int i = 1; i <= 100; i++)


System.out.println("Welcome to Java!");
1. The counter initialization 3. The loop body will
will be executed first. 2. The condition will be be executed third (after
executed second. the condition).

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.

There are other formats too, but not as common as the


above two.

32
animation

Trace for Loop


Declare i
int i;
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");

33
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 1
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");

34
animation

Trace for Loop, cont.


(i < =2) is true
since i is 1
int i;
for (i = 1; i <= 2; i++) {
System.out.println( "Welcome to Java!");
}
System.out.println("Good Bye");

35
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");
Output on the Screen:
Welcome to Java!

36
animation

Trace for Loop, cont.


Execute update statement
int i; i now is 2
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");
Output on the Screen:
Welcome to Java!

37
animation

Trace for Loop, cont.


(i <= 2) is still true
int i; since i is 2
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");
Output on the Screen:
Welcome to Java!

38
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");
Output on the Screen:
Welcome to Java!
Welcome to Java!

39
animation

Trace for Loop, cont.


Execute update statement
int i; i now is 3
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");
Output on the Screen:
Welcome to Java!
Welcome to Java!

40
animation

Trace for Loop, cont.


(i <= 2) is false
int i; since i is 3
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");
Output on the Screen:
Welcome to Java!
Welcome to Java!

41
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 1; i <= 2; i++) {
System.out.println("Welcome to Java!");
}
System.out.println("Good Bye");
Output on the Screen:
Welcome to Java!
Welcome to Java!
Good Bye

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);
} } }

(a) (b) (c)

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

You might also like