Professional Documents
Culture Documents
Lecture8 by Tony - Koo
Lecture8 by Tony - Koo
Iteration
While-loop
Tony.Koo
Loop
int x = 1;
if(x <= 10)
System.out.println(x);
Curly braces {}
The following are NOT equivalent. What is the
output for each?
int x = 7;
while(x <= 10){ Output:
x++; 8 9 10 11
System.out.print(x);
}
int x = 7;
while(x <= 10) Output:
x++; 11
System.out.println(x);
What’s wrong?
int count = 1;
Output:
-2147483648 (Integer.MIN_VALUE)
• Correct!
Output:
10 11 12
Basic Loop Algorithms
Important basic algorithms that use loops:
int sum = 0;
int number = 1;
while(number <= 100){
sum = sum + number;
number++;
}
X1 = 1
X2 = 1
Xn = Xn-1 + Xn-2 (When n >= 3)
Sum(n) = X1 + X2 + X3 + .......+ Xn
while (test1) {
while (test2){
Statements;
}
}
nested While-loop
Print a matrix of * applying
nested while loop:
***** int x = 0;
While(x<4){
***** int y = 0;
While(y<5){
***** System.out.print(“*”);
y++;
***** }
System.out.println();
x++;
}
nested While-loop
Excise:Try to Print the matrix
below:
*
**
***
****
*****
Exercise
Lab 1: Primes
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.
• 24 returns 9 because
2, 3, 5, 7, 11, 13, 17, 19, 23 are primes
less than or equal to 24.
Lab 2
Write a program that repeatedly flips a coin until four heads in a
row are seen. You should use Math.random() to give an equal
chance to a head or a tail appearing. Each time the coin is flipped,
what is seen is displayed (H for heads, T for tails). When four
heads in a row are flipped a congratulatory message is printed.
Here are possible outputs of two calls to fourHeads:
T T T H T H H H H
Four heads in a row!
T H T H T T T T T H H T H H H H
Four heads in a row!
Lab 3
Suppose we have pennies, dimes and quotars, accept a
number of cents from console and print out all possible
combinations of penny, nickel and quotar.
Example: 76 cents could be
3 quotars, 0 dime and 1 penny
2 quotars, 2 dimes and 6 pennies
2 quotars, 1 dime and 16 pennies
2 quotars, 0 dime and 26 pennies
......