0% found this document useful (0 votes)
6 views

L6 - For Loop, Scope, Pseudo-code

The document provides an introduction to programming in Java, focusing on loops, scope, and pseudo-code. It explains the syntax and functionality of for loops, including initialization, testing, and updating variables, as well as the concept of variable scope within loops. Additionally, it covers the Math library, type casting, and nested loops, along with common errors encountered in loop structures.

Uploaded by

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

L6 - For Loop, Scope, Pseudo-code

The document provides an introduction to programming in Java, focusing on loops, scope, and pseudo-code. It explains the syntax and functionality of for loops, including initialization, testing, and updating variables, as well as the concept of variable scope within loops. Additionally, it covers the Math library, type casting, and nested loops, along with common errors encountered in loop structures.

Uploaded by

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

Introduction to Programing

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

• 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");
2
for loop syntax
for (initialization; test; update) { header
statement;
statement;
... body
statement;
}

– Perform initialization once.


– Repeat the following:
• Check if the test is true. If not, stop.
• Execute the statements.
• Perform the update.
3
Initialization
for (int i = 1; i <= 6; 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


• can use any name, not just i
• can start at any value, not just 1

4
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

5
Increment and decrement
shortcuts to increase or decrease a variable's value by 1

Shorthand Equivalent longer version


variable++; variable = variable + 1;
variable--; variable = variable - 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

Shorthand Equivalent longer version


variable += value; variable = variable + value;
variable -= value; variable = variable - value;
variable *= value; variable = variable * value;
variable /= value; variable = variable / value;
variable %= value; variable = variable % 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"

• The for loop does exactly that!


for (int i = 1; i <= 6; i++) {
System.out.println(i + " squared = " + (i *
i));
}

– "For each integer i from 1 through 6, print ..." 8


Loop walkthrough
1 2 3
for (int i = 1; i <= 4; i++) {
4 System.out.println(i + " squared = " + (i * i));
}
5 System.out.println("Whoo!");

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

• Concatenate " " to separate the numbers

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.

public static void example() {


int x = 3;
for (int i = 1; i <= 10; i++) {
System.out.println(x); x's scope
}
// i no longer exists here
}

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

• A variable can't be declared twice or used out of its


scope.
for (int i = 1; i <= 100 * line; i++) {
int i = 2; // ERROR: overlapping scope
System.out.print("/");
}
i = 4; // ERROR: outside scope 15
Scope
public class ScopeExample {
public static void main(String[] args) {
int x = 3;
int y = 7;
computeSum();
}

public static void computeSum() {


int sum = x + y; // ERROR:
System.out.println(“sum = ” + sum);
}
}

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)

• parameter: A value passed to a method by its caller.


• return: To send out a value as the result of a method.
– The opposite of a parameter:
• Parameters send information in from the caller to the method.
• Return values send information out from a method to its caller.

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

• Math.max and Math.min can be used to bound numbers.


Consider an int variable named age.
– What statement would replace negative ages with 0?
– What statement would cap the maximum age to 40? 20
Quirks of real numbers
• Some Math methods return double or other non-int
types.
int x = Math.pow(10, 3); // ERROR: incompat. types

• Some double values print poorly (too many digits).


double result = 1.0 / 3.0;
System.out.println(result); // 0.3333333333333

• The computer represents doubles in an imprecise way.


System.out.println(0.1 + 0.2);

– Instead of 0.3, the output is 0.30000000000000004 21


Type casting
• type cast: A conversion from one type to another.
– To promote an int into a double to get exact division
from /
– To truncate a double from a real number to an integer

• 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

• You can use parentheses to force evaluation order.


– double average = (double) (a + b + c) / 3;

• A conversion to double can be achieved in other ways.


– double average = 1.0 * (a + b + c) / 3;

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
}

• Output: Outer loop inner loop


i=1 j goes from 1 to 10
** * * * * * * * * i=2 j goes from 1 to 10
** * * * * * * * * i=3 j goes from 1 to 10
** * * * * * * * *
** * * * * * * * * i=4 j goes from 1 to 10
** * * * * * * * * i=5 j goes from 1 to 10
i=6 <=5? No then done
• The outer loop repeats 5 times; the inner one 10 times.
– "sets and reps" exercise analogy
25
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("*");
}
System.out.println();
}

• Output: Outer loop inner loop


i=1 j goes from 1 to 1
* i=2 j goes from 1 to 2
**
i=3 j goes from 1 to 3
***
**** i=4 j goes from 1 to 4
***** i=5 j goes from 1 to 5
i=6 <=5? No then done

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

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


for (int j = 1; j <= 10; i++) {
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

• We must build multiple complex lines of output using:


– an outer "vertical" loop for each of the lines
– inner "horizontal" loop(s) for the patterns within each line

29
Outer and inner loop
• First write the outer loop, from 1 to the number of lines.
for (int line = 1; line <= 5; line++) {
...
}

• Now look at the line contents. Each line has a pattern:


– some dots (0 dots on the last line), then a number
....1
...2
..3
.4
5
– Observation: the number of dots is related to the line
number. 30
Mapping loops to
numbers
for (int count = 1; count <= 5; count++) {
System.out.print( ... );
}

– What statement in the body would cause the loop to


print:
4 7 10 13 16

for (int count = 1; count <= 5; count++) {


System.out.print(3 * count + 1 + " ");
}

31
Loop tables
• What statement in the body would cause the loop to
print:
2 7 12 17 22

• To see patterns, make a table of count and the


numbers.
– Each time count goes up by 1, the number should go up
bycount
5. number to print 5 * 5 * count - 3
count
2
– But count * 5 is too great by 3, so we subtract 3.
1 2 5
7
2 7 10
12
3 12 15
4 17 20 17
5 22 25 22
32
Loop tables question
• What statement in the body would cause the loop to
print:
17 13 9 5 1
• Let's create the loop table together.
– Each time count goes up 1, the number printed
should ...?
• Go down by 4 (i.e., -4*count)
– But this multiple is off by a margin of ...???
21, so number
• count we addto
21print -4 * count -4 * count + 21
1 17 -4 17
2 13 -8 13
3 9 -12 9
4 5 -16 5
5 1 -20 1
33
Nested for loop exercise
• Make a table to represent any patterns on each line.
....1 line # of dots -1 * line -1 * line + 5
...2 1 4 -1 4
..3 2 3 -2 3
.4 3 2 -3 2
5 4 1 -4 1
5 0 -5 0

• To print a character multiple times, use a for loop.


for (int j = 1; j <= 4; j++) {
System.out.print("."); // 4 dots
}
34
Nested for loop solution
• Answer:
for (int line = 1; line <= 5; line++) {
for (int j = 1; j <= (-1 * line + 5); j++) {
System.out.print(".");
}
System.out.println(line);
}

• 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.

• Why draw ASCII art?


– Real graphics require a lot of finesse #================#
– ASCII art has complex patterns | <><> |
– Can focus on the algorithms | <>....<> |
| <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
38
Development strategy
• Recommendations for managing complexity:
1. Design the program (think about steps or methods
needed).
• write an English description of steps required
• use this description to decide the methods
#================#
| <><> |
2. Create a table of patterns of characters | <>....<> |
• use table to write your for loops | <>........<> |
|<>............<>|
|<>............<>|
| <>........<> |
| <>....<> |
| <><> |
#================#
39
Pseudo-code
• pseudo-code: An English description of an algorithm.

• Example: Drawing a 12 wide by 7 tall box of stars

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

public static void topHalf() {


for (int line = 1; line <= 4; line++) {
// contents of each line
}
}

public static void bottomHalf() {


for (int line = 1; line <= 4; line++) {
// contents of each line
}
}

public static void line() {


// ...
}
}
42
2. Tables
• A table for the top half:
– Compute spaces and dots expressions from line number

line spaces line * -2 + 8 dots 4 * line - 4

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

You might also like