# Building Java Programs

## Lab 2: Ch. 2: Expressions and Variables, For Loops

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

lab document created by Marty Stepp and Stuart Reges

# Today's lab

Goals for today:

• use expressions and variables for numeric computations
• 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

# Expressions

Recall that Java has expressions to represent math and other computations. Expressions may use operators, which are evaluated according to rules of precedence. Every expression produces a value of a given type.

Type Description Example Result
`int` integers (up to 231 - 1) `3 + 4 * 5` `23`
`double` real numbers (up to 10308) `3.0 / 2.0 + 4.1` `5.6`
`String` text characters `"hi" + (1 + 1) + "u"` `"hi2u"`

# Exercise : Expressions (2.1)

Write the results of each of the following expressions. If you're stuck, ask a TA or neighbor.

 `12 / 5 + 8 / 4` `4` `3 * 4 + 15 / 2` `19` `-(1 + 2 * 3 + (1 + 2) * 3)` `-16` `42 % 5 + 16 % 3` `3` `2.5 * 2 + 17 / 4` `9.0` `4.5 / 3 / 2 + 1` `1.75`

# Exercise : More expressions (2.1)

Write the results of each of the following expressions.

 `5 * 6 / 4 % 3 - 23 / (14 % 6)` `-10` `30 % 9 + 5 % 8 - 11 % 4 % 2` `7` `1 + 9 / 2 * 2.0` `9.0` `46 / 3 / 2.0 / 3 * 4/5` `2.0` `50 / 9 / 2.0 + 200 / 10 / (5.0 / 2)` `10.5`

# Exercise : Expressions

For each expression in the left-hand column, indicate its value in the right-hand column. Be sure to list a constant of appropriate type (e.g., 7.0 rather than 7 for a double, Strings in quotes).

 `4 * (2 + 4) - 3 * 5` `9` `54 % 10 + 8 * 3 % 9` `10` `3 * 2 + 4 + "+" + 2 + 3 * 4` `"10+212"` `2.3 * 3 + 19 / 5 / 2 + 6.0 / 5` `9.1` `108 / 20 * 3 / 4 / 2.0 + 1.0 / 2` `2.0`

# jGRASP Interactions Pane

• jGRASP has a useful feature called the Interactions Pane that allows you to type in Java expressions or statements one at a time and instantly see their results.
• To use it, run jGRASP and then click the "Interactions" tab near the bottom.

continued on the next slide...

# Exercise : Using jGRASP Interactions Pane

In this exercise, you'll use the Interactions Pane to quickly discover the result of some expressions that would be difficult to evaluate by hand. Copy/paste each expression below into the Interactions Pane to evaluate it, then input the answer into this slide.

 `123 * 456 - 789` `55299` `3.14 + 1.59 * 2.65` `7.3535` `2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2` `1024` `2 + 2 + "xyz" + 3 + 3` `"4xyz33"`

(For the last expression, the Interactions Pane doesn't put `""` quotes around Strings when displaying results, so you must add those yourself if needed. For example, if the Interactions Pane gives you a result of `abc123`, it should be written here as `"abc123"`.)

# Variables

Recall that you can use a variable to store the results of an expression in memory and use them later in the program.

```type name;                       // declare
name = value or expression;        // assign a value
...
type name = value or expression;   // declare-and-initialize together
```

Examples:

```double iphonePrice;
iPhonePrice = 499.95;

int siblings = 3;
System.out.println("I have " + siblings + " brothers/sisters.");
```

# 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? Write your answers in the boxes on the right.

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

a = a + 1;            // a? 6
b = b - 1;            // b? 9
c = c + a;            // c? 16
```

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

What are the values of `i`, `j`, and `k` after the following statements?

```int i = 2;
int j = 3;
int k = 4;
int x = i + j + k;

i = x - i - j;            // i? 4
j = x - j - k;            // j? 2
k = x - i - k;            // k? 1
```

# Exercise : `ComputePay`

The following program redundantly repeats the same expressions many times. Download it and open it in jGRASP, then modify the program to remove the redundancy using variables. Use an appropriate type for each variable.

The program's output should be the same after your modifications. No expression should be computed more than once in the code.

# Exercise : Syntax errors

• The following program contains 9 mistakes! What are they? Copy and paste the following code into jGRASP and correct the various mistakes. The answer is on the next 2 slides if you need some help.  ``` 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 + 1; System.out.println("x and y are " + x + and + y); } } ```

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` (should not write the word `int` here)
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);
}
}
```

# `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 : What's the output?

What output is produced by the following Java program? Write the output in the box on the right side.

 ```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; } } } ``` Output: ```32 16 8 4 ```

# 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 : 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: You want to come up with an expression with a multiplier and a constant. First pick a multiplier (if your loop variable goes up by 1 each time, how much do these numbers go up by each time?). Then pick a constant (when your loop variable is 1, this is supposed to be 8, what do you have to add to get this value?).

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

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

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

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