L6 - For Loop, Scope, Pseudo-code
L6 - For Loop, Scope, Pseudo-code
in Java
loops, Scope, Pseudo-code
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");
4
Test
for (int i = 1; i <= 6; i++) {
System.out.println("I am so smart");
}
5
Increment and decrement
shortcuts to increase or decrease a variable's value by 1
int x = 2;
x++; // x = x + 1;
// x now stores 3
double gpa = 2.5;
gpa--; // gpa = gpa - 1;
// gpa now stores 1.5
6
Modify-and-assign
shortcuts to modify a variable's value
x += 3; // x = x + 3;
gpa -= 0.5; // gpa = gpa - 0.5;
number *= 2; // number = number * 2;
7
Repetition over a range
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"
1
Output:
2
1 squared = 1
2 squared = 4 4
3 squared = 9
4 squared = 16
Whoo! 3
9
Multi-line loop body
System.out.println("+----+");
for (int i = 1; i <= 3; i++) {
System.out.println("\\ /");
System.out.println("/ \\");
}
System.out.println("+----+");
– Output:
+----+
\ / First iteration i=1
/ \
\ / Second iteration i=2
/ \
\ / Third iteration i=3
/ \
+----+ Fourth iteration i=4 4<=3? no then stop iterating
10
Expressions for counter
int highTemp = 5;
for (int i = -3; i <= highTemp / 2; i++) {
System.out.println(i * 1.8 + 32);
}
– Output:
26.6
28.4
30.2
32.0
33.8
35.6
11
System.out.print
• Prints without moving to a new line
– allows you to print partial messages on the same line
int highestTemp = 5;
for (int i = -3; i <= highestTemp / 2; i++) {
System.out.print((i * 1.8 + 32) + " ");
}
• Output:
26.6 28.4 30.2 32.0 33.8 35.6
12
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.
13
Scope
• scope: The part of a program where a variable exists.
– From its declaration to the end of the { } braces
• A variable declared in a for loop exists only in that loop.
• A variable declared in a method exists only in that method.
14
Scope implications
• Variables without overlapping scope can have same
name.
for (int i = 1; i <= 100; i++) {
System.out.print("/");
}
for (int i = 1; i <= 100; i++) { // OK
System.out.print("\\");
}
int i = 5; // OK: outside of loop's scope
16
Math Library
Method name Description
Parameters
Math.abs(value) absolute value
and return
Math.round(value) nearest whole number values are
Math.ceil(value) rounds up of type
Math.floor(value) rounds down double
Math.log10(value) logarithm, base 10
Math.max(value1, value2) larger of two values
Math.min(value1, value2) smaller of two values
Math.pow(base, exp) base to the exp power
Math.sqrt(value) square root
Math.sin(value) sine/cosine/tangent of
Math.cos(value) an angle in radians Constant Description
Math.tan(value) Math.E 2.7182818...
Math.toDegrees(value) convert degrees to Math.PI 3.1415926...
Math.toRadians(value) radians and back
Math.random() random double between 0 and 1
17
Parameters and Return (will be
revisited)
- Math.abs(-
42 42)
4
mai 2
n 2.7
1
3
Math.round(2.71
)
18
Example
public class Power {
public static void main(String[] args) {
base 5 exponent 3
double base=5;
double exponent = 3; Result 1125
5
25
double result=1;
//print: My calculation for 5.0^3.0 =
System.out.print("My calculation for " + base + "^"+exponent +" = ");
for (int i = 1; i<=exponent; i++){
result = result *base;
}
System.out.println(result);
//print: Math.pow result of 5.0^3.0 =
System.out.print("Math.pow result of " + base + "^"+exponent +" = ");
result = Math.pow(base,exponent);
System.out.println(result);
}
1st iteration, when i =1, 1<=3, then result = 1 * 5=5
}
2nd iteration, when i =2, 2<=3, then result = 5 * 5=25
Output: 3rdnd iteration, when i =3, 3<=3, then result = 25 * 5=125
My calculation for 5.0^3.0 =
Math.pow result of 5.0^3.0 = 4th iteration, when i =4, 4<=3, no then don’t enter the
125.0 loop
125.0
19
Math questions
• Evaluate the following expressions:
– Math.abs(-1.23)
– Math.pow(3, 2)
– Math.pow(10, -2)
– Math.sqrt(121.0) - Math.sqrt(256.0)
– Math.round(Math.PI) + Math.round(Math.E)
– Math.ceil(6.022) + Math.floor(15.9994)
– Math.abs(Math.min(-3, -5))
• Syntax:
(type) expression
Examples:
double result = (double) 19 / 5; // 3.8
int result2 = (int) result; // 3
int x = (int) Math.pow(10, 3); // 1000
22
More about type casting
• Type casting has high precedence and only casts the
item immediately next to it.
– double x = (double) 1 + 1 / 2; // 1
– double y = 1 + (double) 1 / 2; // 1.5
23
Nested for loops
24
Nested loops
• 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
}
26
Nested for loop exercise
• 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
27
Common errors
• Both of the following sets of code produce infinite
loops:
for (int i = 1; i <= 5; i++) {
for (int j = 1; i <= 10; j++) {
System.out.print("*");
}
System.out.println();
}
28
Complex lines
• What nested for loops produce the following output?
epeated characters on each line)
....1
...2
..3
.4
outer loop (loops 5 times because there are 5 lines)
5
29
Outer and inner loop
• First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}
31
Loop tables
• What statement in the body would cause the loop to
print:
2 7 12 17 22
• Output:
....1 line =1, inner loop counter goes from 1 to -1*1+5 = 4, (print 4 dots)
...2 line =2, inner loop counter goes from 1 to -1*2+5 = 3, (print 3 dots)
..3 line =3, inner loop counter goes from 1 to -1*3+5 = 2, (print 2 dots)
.4 line =4, inner loop counter goes from 1 to -1*4+5 = 1, (print 2 dot)
5 line =5, inner loop test evaluated to false (1<=0)
35
Nested for loop exercise
• What is the output of the following nested for loops?
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
for (int k = 1; k <= line; k++) {
System.out.print(line);
}
System.out.println();
}
• Answer:
.... 1
... 2 2
.. 333
.
4444
55555
36
Nested for loop exercise
• Modify the previous code to produce this output:
....1
...2.
..3..
.4...
5....
• Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.print(line);
for (int j = 1; j <= (line - 1); j++) {
System.out.print(".");
}
System.out.println();
} 37
Drawing complex figures
• Use nested for loops to produce the following
output.
print 12 stars.
for (each of 5 lines) { ************
print a star. * *
* *
print 10 spaces. * *
print a star. * *
* *
} ************
print 12 stars.
40
1.Pseudo-code algorithm
1. Line
• # , 16 =, #
2. Top half
• |
• spaces (decreasing)
• <> #================#
• dots (increasing) | <><> |
• <> | <>....<> |
• spaces (same as above)
•
| <>........<> |
|
|<>............<>|
3. Bottom half |<>............<>|
• top half upside-down | <>........<> |
| <>....<> |
4. Line | <><> |
• # , 16 =, # #================#
41
Methods from
pseudocode
public class Mirror {
public static void main(String[] args) {
line();
topHalf();
bottomHalf();
line();
}
1 6 6 0 0 #================#
| <><> |
2 4 4 4 4
| <>....<> |
3 2 2 8 8 | <>........<> |
|<>............<>|
4 0 0 12 12
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
43
3. Writing the code
• Useful questions about the top half:
– What methods? (think structure and redundancy)
– Number of (nested) loops per line?
#================#
| <><> |
| <>....<> |
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
44
Partial solution
// Prints the expanding pattern of <> for the top half of the figure.
public static void topHalf() {
for (int line = 1; line <= 4; line++) {
System.out.print("|");
for (int space = 1; space <= (line * -2 + 8); space++) {
System.out.print(" ");
}
System.out.print("<>");
for (int dot = 1; dot <= (line * 4 - 4); dot++) {
System.out.print(".");
}
System.out.print("<>");
for (int space = 1; space <= (line * -2 + 8); space++) {
System.out.print(" ");
}
System.out.println("|"); | <><> | 6 spaces & 0 dots
}
} | <>....<> | 4 spaces & 4 dots
| <>........<> | 2 spaces & 8 dots
|<>............<>|0 spaces & 12 dots
45