Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Unit 2: Control Structure

Iteration
For Loops

Tony.Koo
Categories of loops
indefinite loop: One where the number of times its body
repeats is not known in advance.
• Prompt the user until they type a non-negative
number.
• Print random numbers until a prime number is
printed.
• Repeat until the user has types "q" to quit.

The while loop is usually used for indefinite loops.


Categories of loops
definite loop: Executes a known number of times.

• Print "hello" 10 times.


• Find all the prime numbers up to an integer n.
• Print each odd number between 5 and 127.

In this lecture, we will see that a for loop is often used to


implement a definite loop.
Repetition with for loops
• So far, repeating a statement is redundant:
System.out.println("Homer says:");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("I am so smart");
System.out.println("S-M-R-T... I mean S-M-A-R-T");

• Java's for loop statement performs a task many times.


System.out.println("Homer says:");
for (int i = 1; i <= 4; i++) { // repeat 4 times
System.out.println("I am so smart");
}
System.out.println("S-M-R-T... I mean S-M-A-R-T");
for loop syntax
for (initialization; test; update) {
statement;
header
statement;
...
statement; body
}

Perform initialization once.


Repeat the following:
Check if the test is true. If not, stop.
Execute the statements.
Perform the update.
Initialization
for (int i = 1; i <= 4; i++) {
System.out.println("I am so smart");
}
Tells Java what variable to use in the loop
Performed once as the loop begins

The variable is called a loop counter, aka


loop control variable
can use any name, not just i
can start at any value, not just 1
Test
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}

Tests the loop counter variable against a


limit

Uses comparison operators:


< less than
<= less than or equal to
> greater than
>= greater than or equal to
Loop variable can be applied more than just a counter
Repetition over a range
Use a for loop to print:

System.out.println("1 squared = " + 1 * 1);


System.out.println("2 squared = " + 2 * 2);
System.out.println("3 squared = " + 3 * 3);
System.out.println("4 squared = " + 4 * 4);
System.out.println("5 squared = " + 5 * 5);
System.out.println("6 squared = " + 6 * 6);

Intuition: "I want to print a line for each


number from 1 to 6"
Loop variable can be applied more than just a counter
Answer
i <= 6; i++
for ( int i = 1; ) {
System.out.println(i + " squared = " + i * i);
}
System.out.println("Whoo!");

Output:
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
6 squared = 36
Whoo!

System.out.println("Whoo!")
Scope of Loop control variable
loop control variable declared
for(int i=1;i<=4;i++){ inside for statement can only be
known in the for loop block, attemp
System.out.println(i ); to use it outside for loop block will
} cause an compile time error
System.out.println(i ); //compile time error

Correct:
int i;
if needed, it is possible to declare
for(i=1;i<=4;i++){ loop control variavle prior to for
System.out.println(i ); loop statement, so that the loop
} control variable can be used during
the loop and after the loop
System.out.println(i );
Example
Write a for loop to print: 5 9 13 17 21 25

Answer:
for (int i = 5; i <= 25; i += 4) {
System.out.print(i + " ");
}

Note:
It is not suitable to use double or other data type as a loop counter, usually it
should be int
The number of times a loop executes can be calculated by
(largestValue - smallestValue)/step+1
If the loop uses counter <= limit, limit is the largest value.
If the loop uses counter < limit, limit-1 is the largest value that allows the loop to
run.
Counting down
The update can use -- to make the loop count
down.
The test must say > instead of <
System.out.print("T-minus ");
for (int i = 10; i >= 1; i--) {
System.out.print(i + ", ");
}
System.out.println("blastoff!");
System.out.println("The end.");

Output:
T-minus 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
blastoff!
The end.
Nested loopsps
• nested loop: A loop placed inside another loop.
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println(); // to end the line
}
• Output:
**********
**********
**********
**********
**********
• In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of
its iterations before the outer loop can continue to its next iteration.
• The number of times a nested for loop body is executed is the number of times the outer loop runs
multiplied by the number of times the inner loop runs (outer loop runs * inner loop runs).
Nested for loop exercises
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}

• Output:
*
**
***
****
*****
Nested for loop exercises
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.println();
}

• Output:
1
22
333
4444
55555
Nested for loop exercises
• What is the output of the following nested for loops?
for (int i = 1; i <= 5; i++) {
for (int j = i; j <= 5; j++) {
System.out.print(i);
}
System.out.println();
}

• Output:
11111
2222
333
44
5
For vs While
Write a loop to compute the sum:
1 + 2 + 3 + … + 99 + 100

int sum = 0;
int i = 1;
while(i <= 100){
sum += i; Both for and while loops can be
i++; used to solve this problem.
}

int sum = 0;
for(int i = 1; i <= 100; i++){
sum += i;
}
For vs. While
Although for and while loop can generally be interchangeable.
It is best practice to use a for loop as a definite loop where the
beginning and termination of the loop is well defined.

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


System.out.println(i);
}

This for loop executes 100 times. It is a definite loop. It is usually better to
use a for loop as a definite loop.
For vs. While
If the termination condition of a loop is less well defined, use a while loop. For example,
suppose you require a positive integer input from the user. The following will loop until a
positive number is entered.

Scanner inp = new Scanner(System.in);


Sample Output:
System.out.print("Enter a positive number:");
Enter a positive number: -4
int x = inp.nextInt(); Enter a positive number: -5
Enter a positive number: -10
Enter a positive number: 6
while(x <= 0){
Thank you!
System.out.print("Enter a positive number:");
x = inp.nextInt();
}
System.out.print("Thank you!");

This while loop executes an unknown number of times since you don't know when the user
will enter a positive number. It is a indefinite loop. It is better to use a while loop here.
Infinite loop & boundary testing
• Both for loop and while loop will occur infinite loop if forgetting to set up loop control
variable or updating the loop control variable incorrectly

for(int i = 1; i < 10; i--){


System.out.println(“I am looping infinately!!!”) ;
}
• Boundary error: accidently write loop statement repeating one number past or one
number short of the right amount. The real way to avoid this error is to hand-trace the
situation of the loop when it starts and when it comes to the end, so call boundary
testing

for(int i = 0; i <= 10; i++){


System.out.println(i); //How many times?10?
}
Exercise 1
Exercise 2
Lab 1:Primes --apply for loop
1)Write a program that accepts in integer and
then give the number of factors of the integer.
• ie. 24 has 8 factors because
1, 2, 3, 4, 6, 8, 12, and 24 are factors of 24.

2)Write a program which can determine whether


or not an integer is prime.
Example: 27 returns false and 47 returns
true.
Lab 1:Primes --apply for loop

3)Write program that accepts in integer


parameter n returns the number of primes
from 2 to n.

• 24 returns 9 because
2, 3, 5, 7, 11, 13, 17, 19, 23 are primes
less than or equal to 24.
Lab 2: Print the list below --apply for loop
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

You might also like