# University of Washington, CSE 142 (190)

## Lab 2: Expressions, Variables, and Loops

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

lab document created by Whitaker Brand and Marty Stepp

# 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:

• write and evaluate expressions to compute numeric values
• use variables to store results of a computation into memory
• trace and write `for` loops for repeating lines of code
• draw patterned figures of text using loops

# Exercise : Expressions (2.1)

Write the results of each of the following expressions.

 `12 / 5 + 8 / 4` `4` `3 * 4 + 15 / 2` `19` `-(1 + 2 * 3 + (1 + 2) * 3)` `-16` `42 % 5 + 16 % 3` `3` `5 * 6 / 4 % 3 - 23 / (14 % 6)` `-10` `30 % 9 + 5 % 8 - 11 % 4 % 2` `7` `1 + 9 / 2 * 2.0` `9.0` `2.5 * 2 + 17 / 4` `9.0` `4.5 / 3 / 2 + 1` `1.75` `46 / 3 / 2.0 / 3 * 4/5` `2.0` `50 / 9 / 2.0 + 200 / 10 / (5.0 / 2)` `10.5`

# Exercise : Variable declaration syntax

Which of the following choices is the correct syntax for declaring a real number variable named `grade` and initializing its value to `4.0`?

# Exercise : Variable assignment syntax

Suppose you have a variable named `grade`, set to `1.6`:

```double grade = 1.6;   // uh-oh
```

Suppose later in the program's code, we want to change the value of `grade` to `4.0`. Which is the correct syntax to do this?

# Exercise : `a`, `b`, and `c`

What are the values of `a`, `b`, and `c` after the following statements? (It may help you to write down their values after each line.)

```int a = 5;
int b = 10;
int c = b;
a++;
b--;
c = c + a;
```

• `a` : `6`
• `b` : `9`
• `c` : `16`

# Exercise : `i`, `j`, and `k`

What are the values of `i`, `j`, and `k` after the following statements?
(What is this code really doing?)

```int i = 2;
int j = 3;
int k = 4;
i = i * j * k;
j = i / j / k;
k = i / j / k;
i = i / j / k;
```

• `i` : `4`
• `j` : `2`
• `k` : `3`
• The code is "rotating" the values of the three variables, swapping each variable's value for the previous variable's.

# Exercise : Birthday variables

• Create a complete Java program in a class named `Bday` that declares four variables and assigns appropriate values to them.
• the birthday month of another student sitting near you today (1-12)
• the birthday day of that same student near you (1-31)
• Ask your neighbor for their name and for the proper numbers to store in the variables for his/her birthday. Then produce output in this format using your four variables:
• ```My birthday is 9/19, and Suzy's is 6/14.
```

# Exercise : Syntax errors

• The following program contains 9 mistakes! What are they?  ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 ``` ```public class Oops { public static void main(String[] args) { int x; System.out.println("x is" x); int x = 15.2; // set x to 15.2 System.out.println("x is now + x"); int y; // set y to 1 more than x y = int x++; System.out.println("x and y are " + x + and + y); } } ```
• Once you think you've found them all, compile/run your corrected code.

1. line 4: missing `+` between `"x is"` and `x`
2. line 4: cannot print the value of `x` before assigning it a value
3. line 6: cannot assign `15.2` into a variable of type `int`
4. line 6: should not redeclare the variable's type
5. line 7: `"` mark should be between `now` and `+`
6. line 10: should not write the word `int` here
7. line 10: variable `y` should be same type as `x`
8. line 10: does not properly set `y` to be 1 more than `x`
9. line 11: `and` should be in quotes with surrounding spaces

# Exercise - corrected version

• Here is a corrected version of the program:
```public class Oops {
public static void main(String[] args) {
double x = 0.0;
System.out.println("x is" + x);

x = 15.2;       // set x to 15.2
System.out.println("x is now " + x);

double y;       // set y to 1 more than x
y = x + 1;
System.out.println("x and y are " + x + " and " + y);
}
}
```

# Exercise : Equation

Suppose you have a real number variable `x`. Write a Java expression that computes a variable named `y` storing the following value:

y = 12.3x4 - 9.1x3 + 19.3x2 - 4.6x + 34.2

(We haven't learned a way to do exponents yet, but you can simulate them using several multiplications.)

Use the example program on the next slide to test your code.

# Exercise - Example code

Copy/paste this program into jGRASP to test your solution.

```// expected output:
// y is 7043.7

public class EquationY {
public static void main(String[] args) {
double x = 5;

double y = put your expression for y here ;

System.out.println("y is " + y);
}
}
```

```double y = 12.3*x*x*x*x - 9.1*x*x*x + 19.3*x*x - 4.6*x + 34.2;
```

If you want an added challenge, try to come up with a way to compute the above value while using the `*` operator no more than 4 times.

```double y = (((12.3 * x - 9.1) * x + 19.3) * x - 4.6) * x + 34.2;
```

# Exercise : What's the output?

• What output is produced by the following Java program?
```public class OddStuff {
public static void main(String[] args) {
int number = 32;
for (int count = 1; count <= number; count++) {
System.out.println(number);
number = number / 2;
}
}
}
```
```32
16
8
4
```

# Exercise : `for` loop practice

• Copy and paste the following code into jGrasp.
```public class Beer {
public static void main(String[] args) {
for ( fill me in! ) {
System.out.println( fill me in! );
}
}
}
```

continued on the next slide...

# Exercise - expected output

• Modify the code to produce the song 99 Bottles of Beer on the Wall:
```99 bottles of beer on the wall, 99 bottles of beer
Take one down, pass it around, 98 bottles of beer on the wall

98 bottles of beer on the wall, 98 bottles of beer
Take one down, pass it around, 97 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
```
• Use the Output Comparison Tool to check your work. You can set your program to count down from 9 to make it easier to copy the output.

# Exercise : Sequence of numbers

• Write a complete Java program that produces this sequence of numbers using a `for` loop:
```8
11
14
17
20
23
```
• (Hint: making a table is a helpful way to quantify and visualize patterns.)

# Exercise : Sequence of characters

• Modify the code from the previous exercise to produce the following output:
```********
***********
**************
*****************
********************
***********************
```
• Use the Output Comparison Tool to check your work.
• (Hint: Note the number of stars in each row. Instead of printing the number 8, now you're printing 8 stars. You will now need a nested loop.)

# Exercise : What's the output?

• What output is produced by the following Java method?
```public static void stars() {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
for (int j = 1; j <= 20 - 2 * i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println();
}
}
```
• (Try to figure it out without running the code...
If you give up, copy and paste it into jGrasp and run it!)
• Hint: Think of each inner loop from 1 to X as a loop that prints X copies of the given character.

```*                  *
**                **
***              ***
****            ****
*****          *****
******        ******
*******      *******
********    ********
*********  *********
********************
```

# Exercise : What's the output?

• What's the output of the following Java method?
```public static void mystery() {
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
```
• (Try to figure it out without running the code...
If you give up, copy and paste it into jGrasp and run it!)
• Recall: `\t` represents a tab character.

```1	2	3	4	5	6	7	8	9	10
2	4	6	8	10	12	14	16	18	20
3	6	9	12	15	18	21	24	27	30
4	8	12	16	20	24	28	32	36	40
5	10	15	20	25	30	35	40	45	50
6	12	18	24	30	36	42	48	54	60
7	14	21	28	35	42	49	56	63	70
8	16	24	32	40	48	56	64	72	80
9	18	27	36	45	54	63	72	81	90
10	20	30	40	50	60	70	80	90	100
```

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

# Exercise : printing a design

• Write a complete Java program to produce the following output:
```-----1-----
----333----
---55555---
--7777777--
-999999999-
```
• 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 Chapter 2 and try to solve them! We suggest doing some Exercises related to loops.