## Jam 2: Study Guide

Jams are open book. 40 minutes in lab.

Topics:

This quiz includes the previous topics from Jam 1 plus

• Conditional statements: `if`/`else`

• Logical and relational operators: `&&`, `||`, `!`, `⇐`, `>=`, `>`, `<` , `==`

• Arithmetic operators: `+`, `-`, , `/`, `++`, `--`, `+=` , `-=`, `=`, `/=`

• String comparisons, the empty string: `""`

• loops: for- and while-

• Accumulator variable pattern

## Practice questions

1) Given the following variables, what is the value and type for each of the following expressions?

``````int x = 5;
int y = 13;
String message = "cat!";
boolean Done = false;``````
• `x < 10 && y < 10`

• `x < 10 || y < 10`

• `x < 10 && x > 0`

• `x > 10 || x < 0`

• `(5/x) > 7.0`

• `message.compareTo("cats") == 0`

• `!Done`

• `Done || (x < 6 && y > 10)`

2) Consider the following code

``````String colorName = "purple";

if (colorName.compareTo("red") != 0) {
System.out.println(colorName + " is not primary");
}
else if (colorName.compareTo("blue") != 0 {
System.out.println(colorName + " is not primary");
}
else if (colorName.compareTo("yellow") != 0) {
System.out.println(colorName + " is not primary");
}
else {
System.out.println(colorName + " is primary");
}``````
• Draw a decision diagram corresponding to this if statement.

• What does the above code print when

• `colorName = "purple"`?

• `colorName = "red"`?

• `colorName = "yellow"`?

3) Write a program that inputs a month as an integer and returns a string name for that month. For example, if we call the function with the number 1, the program should print "January".

``````\$ java Month
Enter an integer: 1
January

\$ java Month
Enter an integer: 10
October``````

4) Consider the following loop

``````int pinLength = 4;
String pin = "";
for (int i = 0; i < pinLength; i++) {
pin = pin + "*";
System.out.println(pin);
}
• What is output to the console when we run this program?

• Convert the loop above so it uses a while loop instead of a for loop

5) Show the output from the following code fragment:

``````for (int x = 0; x < 6; x++) {
System.out.println(x + " " + x*x);
}
System.out.println("done!")``````

6) Consider the following program

``````int x = 3;
System.out.println("0  " + x);
for (int i = 0; i < 5; i++) {
if (x % 2 == 0) {
x = x / 2;
}
else {
x = ( 3*x + 1 ) / 2;
}
System.out.println(i + " " + x);
}``````
• Trace the program and show its output.

• Create a table having columns for `i`, and `x` and show how the values change as the loop executes.

7) Write a program that asks the user how many grades they want to average, prompts the user for those grades, and prints the average.

``````Enter number of grades to average: 5

``````Enter a word: repetitive