# University of Washington, CSE 142

## Lab 2: for loops and parameters

Except where otherwise noted, the contents of this document are Copyright 2011 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges, and Whitaker Brand

# Basic lab instructions

• We encourage you to talk to your classmates for help. You can even work on the lab with a partner if you like.
• You may want to bring your textbook to future labs to look up syntax and examples.
• Stuck? Confused? Have a question? Ask a TA for help, or look at the book or past lecture slides.
• You probably won't finish all of the exercises. Just do as much as you can within the allotted time. You don't need to keep working on these exercises after you leave the lab.
• Before you leave today, make sure to check in with one of the TAs in the lab to get credit for your work.

# Today's lab

Goals for today:

• trace and write `for` loops for repeating lines of code
• draw patterned figures of text using loops
• use class constants to represent common unchanging values
• learn the basics of declaring and passing parameters to methods

# `for` loops

A `for` loop repeats a group of statements a given number of times.

```for (initialization; test; update) {
statement(s) to repeat;
}
```

Example:

```for (int i = 1; i <= 10; i++) {
System.out.println("We're number one!");
}
```

# Exercise : simple `for` loop

• Copy/paste the following code into jGRASP.
```public class Count2 {
public static void main(String[] args) {
for ( fill me in! ) {
System.out.println( fill me in! );
}
}
}
```
• Modify the code to produce the following output:
```2 times 1 = 2
2 times 2 = 4
2 times 3 = 6
2 times 4 = 8
```

# Exercise : Verify solution in Practice-It!

Our Practice-It! system lets you solve Java problems online.

• Go to the Practice-It! web site.
• Create an account if you don't have one, and log in.
• Under the "CS1 Labs", "Lab 2" category, select the "simple for loop" problem. (direct link)
• Copy/paste your program from jGRASP into Practice-It, and submit. If it does not pass the test, modify your code and re-submit it.

# Exercise : Bottles of beer

• Write a `for` loop that produces the song Bottles of Beer on the Wall:
```10 bottles of beer on the wall, 10 bottles of beer
Take one down, pass it around, 9 bottles of beer on the wall

9 bottles of beer on the wall, 9 bottles of beer
Take one down, pass it around, 8 bottles of beer on the wall

... (output continues in the same pattern) ...

1 bottles of beer on the wall, 1 bottles of beer
Take one down, pass it around, 0 bottles of beer on the wall
```
• Write and test your code in Practice-It! by clicking the checkmark icon at the top of the slide.

# Exercise : jGRASP Debugger

• Breakpoints help you debug programs (tutorial). Copy/paste this code into jGRASP:  ``` 1 2 3 4 5 6 7 8 9 10 ``` ```public class Numbers { public static void main(String[] args) { int number = 42; for (int i = 1; i <= 1000; i++) { number = number * 37 % 103; } int number2 = number * number; System.out.println("result = " + number2); } } ```
• Set a breakpoint on the statement inside the `for` loop (line 5). Do this by moving your cursor to the beginning of that line until you see a stop-sign icon and then clicking.

continued on the next slide...

# Exercise - jGRASP Debugger

• Now you can debug the program by clicking on the debug icon (looks like a ladybug).
• It will stop every time it hits line 5. Then you can see the values of variables `i` and `number`.
• To continue running, press the top-left play or step buttons.
• Using this approach, fill in the table below indicating what value `number` has when `i` has the given value. Keep in mind that you are figuring out what value `number` has just before it executes this line of code.  `i = 1, number = ` `42` `i = 2, number = ` `9` `i = 3, number = ` `24` `i = 4, number = ` `64`

continued on the next slide...

# Exercise - jGRASP Debugger

• Click on the stop-sign a second time to get rid of it and then set a new stop point on line number 7. This will allow you to find out the value of `number` after the loop is done executing.
• Again press "play" to start the programming running again.
• At line 7, what is the value of `number`? 69

# Exercise : `for` loop table practice

Create a table of the number of stars on each line:

```*******
*****
***
*
```
line stars
`1`
`7`
`2`
`5`
`3`
`3`
`4`
`1`

multiplier: How much does the # of stars change between lines? -2

shift: Given your multiplier, what must be added to get that many stars on line 1? 9

Test your loop expression in Practice-It! using the checkmark icon above. Use the form:

```for (int stars = 1; stars <= multiplier * line + shift; stars++) {
```

# Exercise : printing a design

Write a program to produce the following output using nested `for` loops. Use a table to help you figure out the patterns of characters on each line.

```-----1-----
----333----
---55555---
--7777777--
-999999999-
```
Line Dashes Numbers
`1`
`5`
`1`
`2`
`4`
`3`
`3`
`3`
`5`
`4`
`2`
`7`
`5`
`1`
`9`
dashes expression
`-1`
`* line + `
`6`
numbers expression
`2`
`* line + `
`-1`

Test your loop expressions in Practice-It! using the checkmark icon above. Use your expressions in the loop tests of the inner loops of your code.

# Exercise : SlashFigure

Write a Java program in a class named `SlashFigure` to produce the following output with nested `for` loops. Use a loop table if necessary to figure out the expressions.

```!!!!!!!!!!!!!!!!!!!!!!
\\!!!!!!!!!!!!!!!!!!//
\\\\!!!!!!!!!!!!!!////
\\\\\\!!!!!!!!!!//////
\\\\\\\\!!!!!!////////
\\\\\\\\\\!!//////////
```
Line `\` `!` `/`
`1`
`0`
`22`
`0`
`2`
`2`
`18`
`2`
`3`
`4`
`14`
`4`
`4`
`6`
`10`
`6`
`5`
`8`
`6`
`8`
`6`
`10`
`2`
`10`
multiplier
`2`
`-4`
`2`
shift
`-2`
`26`
`-2`

Test your code in Practice-It! or the Output Comparison Tool.

# Class constants

A class constant is a global value that cannot be changed.

```public static final type name = expression;
```

Example:

```public static final int DAYS_PER_WEEK = 7;
public static final double TAX_RATE = 0.10;
```

# `for` loop expressions w/ constant

When adding a class constant to a loop expression, it affects the constant that must be added in the expression. Suppose we have the two loop expressions below for figure sizes of 5 and 9. The third line of the table shows the general formula that would be used if we turned our figure's size into a constant named `SIZE`.

size expression relationship
`5` `8 * line + 16` `16 = 3 * 5 + 1`
`9` `8 * line + 28` `28 = 3 * 9 + 1`
`SIZE` `8 * line + (3 * SIZE + 1)`

continued on the next slide ...

# Exercise : `for` loop table w/ constant

You already found loop expressions for the slash figure at size 6. Now make a table at size 4 and use the two to generalize the loop expression in terms of a constant for the figure size.

```!!!!!!!!!!!!!!
\\!!!!!!!!!!//
\\\\!!!!!!////
\\\\\\!!//////
```
Line `\` `!` `/`
`1`
`0`
`14`
`0`
`2`
`2`
`10`
`2`
`3`
`4`
`6`
`4`
`4`
`6`
`2`
`6`
`\` and `/`
size 6 ` 2 * line + `
`-2`
size 4 ` 2 * line + `
`-2`
size SIZE ` 2 * line + `
`-2`
`!`
size 6 `-4 * line + `
`26`
size 4 `-4 * line + `
`18`
size SIZE `-4 * line + ` `(`
`4`
` * SIZE + `
`2`
`)`

# Exercise : SlashFigure2

• Add a class constant to your slash figure program so that it can be resized from its default of 6:

size 4 size 7
```!!!!!!!!!!!!!!
\\!!!!!!!!!!//
\\\\!!!!!!////
\\\\\\!!//////
```
```!!!!!!!!!!!!!!!!!!!!!!!!!!
\\!!!!!!!!!!!!!!!!!!!!!!//
\\\\!!!!!!!!!!!!!!!!!!////
\\\\\\!!!!!!!!!!!!!!//////
\\\\\\\\!!!!!!!!!!////////
\\\\\\\\\\!!!!!!//////////
\\\\\\\\\\\\!!////////////
```

Test your code in the Output Comparison Tool.

# Parameters

A parameter allows you to pass in a value to a method as you call it.

```public static void name(type name) {   // declare
```
```methodName(expression);                // call
```

Example:

```public static void squared(int num) {
System.out.println(num + " times " + num + " is " + (num * num));
}
...
squared(3);          // 3 times 3 is 9
squared(8);          // 8 times 8 is 64
```

# Exercise : Parameters output

• What two values are printed by each call below? Write them in the boxes provided.
```public class MysteryNums {
public static void main(String[] args) {
int x = 15;
sentence(x, 42);      // 15 42

int y = x - 5;
sentence(y, x + y);   // 10 25
}

public static void sentence(int num1, int num2) {
System.out.println(num1 + " " + num2);
}
}
```

# Solving "Parameter Mystery" problems

• Note the values passed, the order in which they are passed, and the order the method prints them.
```public class MysterySoda {
public static void main(String[] args) {
String soda = "coke";
String pop = "pepsi";
String pepsi = "soda";

// #1 = "coke", #2 = "pepsi", #3 = "soda"
carbonated(soda, pop, pepsi);
}
//                                    #1           #2           #3
public static void carbonated(String coke, String soda, String pop) {
//                           #2               #3             #1
System.out.println("say " + soda + " not " + pop + " or " + coke);
}
}
```
• output: `// say#2pepsi not#3soda or#1coke`

# Exercise : Parameter Mystery

• Fill in the boxes with the output that each method call would produce:
```public class MysterySoda {
public static void main(String[] args) {
String soda = "coke";
String pop = "pepsi";
String coke = "pop";
String pepsi = "soda";
String say = pop;

carbonated(soda, pop, pepsi);        // say pepsi not soda or coke
carbonated(coke, soda, pop);         // say coke not pepsi or pop
carbonated(pop, pepsi, pepsi);       // say soda not soda or pepsi
carbonated("pop", pop, "koolaid");   // say pepsi not koolaid or pop
carbonated(say, "say", pop);         // say say not pepsi or pepsi
}
public static void carbonated(String coke, String soda, String pop) {
System.out.println("say " + soda + " not " + pop + " or " + coke);
}
}
```

# Exercise : Syntax errors

• The following Java program has 9 errors. Can you find all of them?  ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ``` ```public class Parameters { public static void main() { double bubble = 867.5309; double x = 10.01; printer(double x, double y); printer(x); printer("barack", "obama"); System.out.println("z = " + z); } public static void printer(x, y double) { int z = 5; System.out.println("x = " + double x + " and y = " + y); System.out.println("The value from main is: " + bubble); } } ```
• Copy and paste the code into jGrasp and see if you can fix the errors.

1. line 5: cannot use variable `y` without declaring and initializing it
2. line 5: cannot declare the type of `y` in the method call
3. line 6: cannot call `printer` without the correct number of parameters (2, in this case)
4. line 7: cannot call `printer` by passing the correct type of parameters (double, in this case)
5. line 8: cannot refer to the variable `z`: it is in scope inside `printer`, not `main`
6. line 11: must provide a type for `x`
7. line 11: must provide a variable name for the second parameter
8. line 12: must refer to the parameters using the exact same spelling
9. line 13: cannot refer to variables in `main` that were not passed into `printer` as a parameter

# Exercise - Corrected version

• Here is a corrected version of the program:
```public class Parameters {
public static void main() {
double bubble = 867.5309;
double x = 10.01;
double y = 5.3;
printer(double x, double y);
printer(x, 0.0);
printer("barack", "obama");
int z = 5;
System.out.println("z = " + z);
}

public static void printer(double x, double y) {
System.out.println("x = " + x + " and y = " + y);
System.out.println("The value from main is: " + bubble);
int z = 5;
}
}
```

# Exercise : `printSquare`

• Write a method `printSquare` that accepts min and max integers and prints a square of lines of increasing numbers. The first line should start with the minimum; each line that follows should start with the next-higher number. The numbers on a line wrap back to the minimum after it hits the maximum. For example, the call:
```printSquare(3, 6);
```
should produce the following output:
```3456
4563
5634
6345
```
• If the maximum passed is less than the minimum, the method produces no output. Check your answer using Practice-It from the check-mark icon above.

# Exercise : `printGrid`

• Write a method named `printGrid` that accepts two integers representing a number of rows and columns and prints a grid of integers from 1 to (rows*columns) in column-major order.
• For example, the call:
```printGrid(4, 6);
```
should produce the following output:
```1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24
```

# Exercise : Parameter Mystery

• Fill in the boxes with the output that each method call would produce:
```public class MysteryNumbers {
public static void main(String[] args) {
String one = "two";
String two = "three";
String three = "1";
int number = 20;

sentence(one, two, 3);                  // three times two = 6
sentence(two, three, 14);               // 1 times three = 28
sentence(three, three, number + 1);     // 1 times 1 = 42
sentence(three, two, 1);                // three times 1 = 2
sentence("eight", three, number / 2);   // 1 times eight = 20
}
public static void sentence(String three, String one, int number) {
System.out.println(one + " times " + three + " = " + (number * 2));
}
}
```

# Exercise : Parameter Mystery

• Fill in the boxes with the output that each method call would produce:
```public class Mystery {
public static void main(String[] args) {
String song = "good";
String good = "hear";
String walk = "talk";
String talk = "feel";
String feel = "walk";
claim(feel, song, feel);       // to walk the walk is good
claim(good, hear, song);       // to hear the good is bad
claim(talk, "song", feel);     // to feel the walk is song
claim("claim", talk, walk);    // to claim the talk is feel
}

public static void claim(String hear, String good, String song) {
System.out.println("to " + hear + " the " + song + " is " + good);
}
}
```

# Exercise : Number lines, part 1

• Write some nested `for` loops to produce the following output:
```000111222333444555666777888999
000111222333444555666777888999
000111222333444555666777888999
```
• You can use the Output Comparison Tool to check your work.

# Exercise : Number lines, part 2

• Modify the previous code to have it do something a little different:
```99999888887777766666555554444433333222221111100000
99999888887777766666555554444433333222221111100000
99999888887777766666555554444433333222221111100000
99999888887777766666555554444433333222221111100000
99999888887777766666555554444433333222221111100000
```
• You can use the Output Comparison Tool to check your work.

# Exercise : Number lines, part 3

• Modify the code to have it produce this output:
```999999999888888887777777666666555554444333221
999999999888888887777777666666555554444333221
999999999888888887777777666666555554444333221
999999999888888887777777666666555554444333221
```
• You can use the Output Comparison Tool to check your work.

# If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from the book and try to solve them!