0% found this document useful (0 votes)
22 views34 pages

Java Loop Control Statements Explained

This document is a tutorial on Java programming focusing on control flow statements, including while, do-while, and for loops. It provides examples and exercises to help learners understand how to implement these loops and their variations, such as nested loops. The document also emphasizes the importance of avoiding infinite loops and includes practical coding challenges for practice.

Uploaded by

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

Java Loop Control Statements Explained

This document is a tutorial on Java programming focusing on control flow statements, including while, do-while, and for loops. It provides examples and exercises to help learners understand how to implement these loops and their variations, such as nested loops. The document also emphasizes the importance of avoiding infinite loops and includes practical coding challenges for practice.

Uploaded by

shan78945
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Full Stack

🗙
Software Engineering

🗙
Java Repetition
By Max Wong

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


2

What will you learn?


• Understand the while statement
• Understand the do-while statement
• Understand the for statement
• Understand nested loops
• Understand the break and continue flow-control statements

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


3

The while-loop Statement

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


4

只要仲係啱,
The while Statement 就要繼續做。

• As long as (i.e. while) condition


is true, repeatedly execute
statement.
• When condition evaluates to
false, execute
next_statement.
Syntax in Java

while (condition) {
statement;
}
next_statement;
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
public class ForExample { 5

Example 1
public static void main(String [] args) {
int i=1;
while (i <= 4) {
[Link](i);
i++;
}
[Link](”Done”);
}
}

Round i Output
1 1 1
2 2 2
3 3 3
4 4 4
5 5 Done

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


public class ForExample { 6

Example 2
public static void main(String [] args) {
int i=1, sum=0;
while (i <= 4) {
sum += i;
i++;
}
[Link]("Sum = " + sum);
}
}

sum i
Round 1 i= 1 true sum = 0 + 1 1 2
Round 2 i= 2 true sum = 1 + 2 3 3
Round 3 i= 3 true sum = 3 + 3 6 4
Round 4 i= 4 true sum = 6 + 4 10 5 Console output
Round 5 i= 5 false Sum = 10
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
7

Challenge import [Link].*;


public class ForChallenge {
public static void main(String [] args) {
Can you guess what is the use of this
Scanner keyboard = new Scanner([Link]);
program? int count = 0, n, value, sum = 0;

[Link]("How many? ");


How many? 3
n = [Link]();
value? 10
value? 15
while (count < n) {
value? 3
[Link]("value? ");
Sum = 28
value = [Link]();
sum += value;
count ++;
Answer: }
Input n numbers and get their sum [Link]("Sum = " + sum);
}
}

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


8

Infinite Loop using while

import [Link].*;
• The loop never ends
• Stop the program using Ctrl-C public class InfiniteLove {
public static void main(String [] args) {
in keyboard while (true) {
• The break statement can be [Link]("I love you!");
used for terminating the loop }
}
(we saw this in switch }
statement)
Be very careful when using infinite loop. It can
slow down and finally hang your computer when
running out of memory.

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


9

In-class Exercise
Write a program to get a positive number (N) from the
user and calculate the sum of the first N natural number
with a while loop.
End the program by inputting a non-positive number and
display “Bye Bye~”.
Number: 3
Sum = 6
Bye Bye~

Number: -3
Bye Bye~

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


10

咩都唔理做左先,
The do-while Statement 啱既咪繼續做囉。

• Similar to while

• But statement is executed before the


condition check

• Therefore, the statement is executed


at least once Syntax in Java
do {
statement;
} while (condition);

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


next_statement;
11

Example

import [Link].*;
public class DoWhileExample{
public static void main(String [] args) {
Scanner keyboard = new Scanner([Link]);
Input a positive number: -3
int number;
Input a positive number: -10
do {
Input a positive number: 0
[Link]("Input a positive number: ");
Input a positive number: 100
number = [Link]();
Great.
} while (number <= 0);
[Link](“Great.");
}
}

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


12

The for-loop Statement


直面高牆,
辦法總是在你面前

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


13

The for Statement


1. The initializer initiates (初始化)
the variable used in the condition.
2. Similar to the while-loop statement:
As long as the condition is true,
execute statement.
3. After executed the statement,
updater updates the variable used in
the condition. Syntax in Java

4. Repeats step 2 & 3 until the condition is for (initializer; condition; updater) {
false in step 2 and finally executes statement;
}
next_statement. next_statement;
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
14

Example
Round 1 i = 0 true 5 i++ i becomes1 import [Link].*;
public class ForExample {
Round 2 i = 1 true 4 i++ i becomes 2 public static void main(String [] args) {
Round 3 i = 2 true 3 i++ i becomes 3 Scanner keyboard = new Scanner([Link]);
int cnt;
Round 4 i = 3 true 2 i++ i becomes 4
[Link]("How many? ");
Round 5 i = 4 true 1 i++ i becomes 5 cnt = [Link]();
Round 6 i = 5 false n/a n/a n/a
for (int i=0; i<cnt; i++){
How many? 5 [Link](cnt - i);
5 }
4 [Link]("Go!");
3 }
2 }
1
Go!
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
15

Example
Round 1 i = 0 true 5 i++ i becomes1 import [Link].*;
public class ForExample {
Round 2 i = 1 true 4 i++ i becomes 2 public static void main(String [] args) {
Round 3 i = 2 true 3 i++ i becomes 3 Scanner keyboard = new Scanner([Link]);
int cnt;
Round 4 i = 3 true 2 i++ i becomes 4
[Link]("How many? ");
Round 5 i = 4 true 1 i++ i becomes 5 cnt = [Link]();
Round 6 i = 5 false n/a n/a n/a
for (int i=cnt; i>0; i--){
How many? 5 [Link](i);
5 }
4 [Link]("Go!");
3 }
2 }
1
Go!
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
16

Declare Variable in the for Statement


import [Link].*;
public class ForExampleOne {
public static void main(String [] args) {
Scanner keyboard = new Scanner([Link]);
int cnt;

...

[Link]("How many? ");


cnt = [Link]();
In Java, a variable can be declared
when you need it, not necessarily at
for (int i=0; i<cnt; i++){
the beginning of a block
[Link](cnt - i);
}
[Link]("Go!");
}
}
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
17

Example
import [Link].*;
public class Factorial {
public static void main(String [] args) {
Scanner keyboard = new Scanner([Link]);
int n, factorial=1;

[Link]("How many? "); How many? 4


n = [Link](); The factorial of 4 is 24

for (int i=1; i<=n; i++){ (1 x 2 x 3 x 4 = 24)


factorial *= i;
}
[Link]("The factorial of " + n + " is " + factorial);
}
}
FYI:
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
N! = 1 x 2 x 3 x … x N
18

Infinite Loops using for


for (int i = 0; i<100; i--) {
i goes 0, -1, -2, -3, -4, -5, …
[Link]("Hello");
}

for (int i = 1; i != 100; i += 2) {


i goes 1, 3, 5, …, 99, 101, …
[Link]("Hello");
}

for (int i = 98; i < 100; i /= 2){


i goes 98, 49, 24, …, 0, 0, 0, …
[Link]("Hello");
}

Make sure your loop is able to


terminate!

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


19

In-class Exercise
Using for-loop to write a program to get a positive
number (N) from the user and calculate the sum of the
first N natural number with a while loop.
End the program by inputting a negative number and
display “Bye Bye~”.
Number: 3
Sum = 6
Bye Bye~

Number: -3
Bye Bye~

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


20

Nested Loops

繼續努力!

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


21

Hint of Dealing with Nested Loops


import [Link].*;
public class AsteriskBlock { When this outer loop runs:
public static void main(String [] args) {
for (int i = 1; i <= 3; i++) { i equals 1 Loop body

i equals 2 Loop body


Loop body
i equals 3 Loop body
}
}
You don’t have to know the details of
}
the loop body. It is executed three
times anyway.

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


22

Example(1)
import [Link].*; With the hints in the previous
public class AsteriskBlock { slide, can you guess what is
public static void main(String [] args) {
the result of this program?
for (int i = 1; i <= 3; i++) {
for (int j=1; j <= 5; j++) {
[Link]("*"); • j goes from 1 to 5
} • [Link](“*”);
[Link](); • *****
} • When the inner loop finishes
• [Link]();
}
} i equals 1
*****
i equals 2 *****
*****
***** *****
i equals 3
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
23

Example(2)
import [Link].*; i=1 j=1 * *
public class AsteriskBlock { * **
i=2 j=1 i=4 j=1
public static void main(String [] args) { * ***
*
for (int i = 1; i <= 4; i++) { *
i=2 j=2 *
**
for (int j = 1; j <= i; j++) { **
* i=4 j=2
[Link]("*"); ***
} i=3 j=1 ** **
[Link](); *
} *
* **
} i=3 j=2 ** i=4 j=3
***
} ** ***
*
Can you guess what is the i=3 j=3 **
*
**
result of this program? *** i=4 j=4
***
****
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
24

Example(3)
import [Link].*; i=4 j=4 * ****
public class AsteriskBlock { i=4 j=3 ** i=2 j=2 ***
public static void main(String [] args) { *
i=4 j=2 ***
****
for (int i = 4; i >= 1; i--) { i=4 j=4 **** i=2 j=2 ***
for (int j = 1; j <= i; j++) { **** *
i=3 j=3
[Link]("*"); * ****
} ***
**** i=2 j=1
[Link](); i=3 j=2
} ** **
} **** ****
i=3 j=1
} *** ***
i=1 j=1
**
Can you guess what is the *
result of this program?

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


25

Example(4) i equals 1
(int j=1; j <= 3; j++)

(int j=1; j <= 1; j++)


*
for (int i=1; i <= size; i++) { (int j=1; j <= 2; j++)
i equals 2
for (int j=1; j <= size-i; j++) { (int j=1; j <= 2; j++)
**
[Link](" ");
} (int j=1; j <= 1; j++)
i equals 3
(int j=1; j <= 3; j++)
***
for (int j=1; j <= i; j++) {
[Link]("*");
} (int j=1; j <= 0; j++)
i equals 4
(int j=1; j <= 4; j++)
****
[Link]();
}
size? 4
*
**
***
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab ****
26

In-class Exercise
Write a Java application that asks the user to input the size and prints a
corresponding half-diamond. Like below.
size? 4 size? 5 size? 7
* * *
** ** **
*** *** ***
**** **** ****
*** ***** *****
** **** ******
* *** *******
** ******
* *****
****
***
**
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab example_projects/L007_HalfDiamond
*
27

Challenge Exercise
Write a Java application that ask the user to input the size and prints a
corresponding full-diamond. Like below.
size? 4 size? 5 size? 7
h is in
ve t
* * *
’s lea la b
*** *** ***
Let in-clas s
your
***** ***** *****
******* ******* *******
***** ********* *********
*** ******* ***********
* ***** *************
*** ***********
* *********
*******
*****
***
Prepared by Jeffrey Chan and Max Wong in Venturenix Lab
*
28

Further Flow Control:


break and continue

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


29

The break Statement


• When a program executes a break
statement in a loop, it immediately
terminate the loop and execute the
next statement outside the loop

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


30

Example with while Loop


import [Link].*;
public class BreakingWhileExample {
public static void main(String [] args) {
Scanner keyboard = new Scanner([Link]);
int n;
while (true) {
n = [Link](); 10
if (n <= 0){ Square of 10 = 100
break; 16
}else{ Square of 16 = 256
[Link]("Square of " + n + " = " + (n * n)); 0
} Bye~
}
[Link]("Bye~");
}
}

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


31

Example with for Loop


import [Link].*;
public class BreakingForExample {
public static void main(String [] args)
{
Scanner keyboard = new Scanner([Link]);
int i, x; Be careful! i++ has not been executed
for (i=0; i<10; i++ ) { after break.
[Link]("i=" + i + "\tx=? ");
x = [Link]();
if (x == 0){
break;
} i=0 x=? 10
} i=1 x=? 40
[Link]("i=" + i); i=2 x=? 80
[Link]("Bye!"); i=3 x=? 0
} i=3
} Bye!

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


32

The continue Statement


• It stops the current iteration of a
loop and begins the next
iteration.

• “Skip the rest, proceed to the


next.”

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


33

Example
import [Link].*; x=? 1
public class ContinueForExample { x=? -1
public static void main(String [] args) { x=? 2
Scanner keyboard = new Scanner([Link]); x=? -2
int x, sum=0; x=? 3
Sum = 6
for (int i=0; i<5; i++) { Skip the rest when x is
[Link]("x=? "); not positive.
x = [Link]();
if (x <= 0){
continue;
} Continue can also be applied to while
sum += x; and do-while.
}
[Link]("Sum = " + sum);
}
}

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab


34

What did you learn?


• Understand the while statement
• Understand the do-while statement
• Understand the for statement
• Understand nested loops
• Understand the break and continue flow-control statements

Prepared by Jeffrey Chan and Max Wong in Venturenix Lab

You might also like