Welcome to Lesson 11!

Learning Objectives
By the end of today's class, you should know...
• What is a loop?
• What are the 3 parts of any loop?
• How do you structure a while loop?
• What are 4 common uses of while loops?
• What are some other common mistakes people make when writing loops?

Announcements

• Quiz 5 and Lab 5 due on Friday
• Assignment 11 due Tuesday
• Enjoy the 3-day weekend! :)

Review Activity
With a partner, answer the following questions on a sheet of paper:
• Write one statement to print out the value of the following variable to exactly 5 decimal places:
final double PI = 3.1415926535;
• The below program contains some magic numbers. Fix the problem without changing the outcome of the program:
System.out.println("The area of the triangle is: " + .5 * 7 * 8);
• What will the following output to the console?
String student1 = "Li";
String student2 = "Lee";

if (student1.compareTo(student2) < 0) {
System.out.println("Alpha");
} else {
System.out.println("Beta");
}

### Assignment Operators

• As we discussed before, we assign values to variables using an equal (`=`) sign
`int sum = 0;`
• However, the equal sign is really an assignment operator and does not denote equality
• Thus, unlike math, we can have the same variable on both sides of an equals sign:
```int sum = 25;    // initialize sum to 25
sum = sum + 10;  // add to sum
```
• Note that the value of the variable is changed in the second line
• Reading variables from memory does not change them
• Values placed into a variable replace (overwrite) previous values:

### Shortcut Assignment Operators

• We can use additional operators to calculate values and assign them to the variable on the left all in one statement
• Known as shortcut assignment operators
• The general syntax is:
`variable op= expression;`
• Where op is one of the five arithmetic operators: `+``-``*``/``%`
• For example, the following two statements create the same result:
```x = x + 3;
x += 3;
```
• Shown below are the assignment operators with examples of how they are used:

#### Summary of Assignment Operators

Operator Description Example Equivalent To
`=` Assigns the value of the expression on the right to the variable on the left `x = 3`
`+=` Adds the expression on the right to the variable on the left `x += 3` `x = x + 3`
`-=` Subtracts the expression on the right from the variable on the left `x -= 3` `x = x - 3`
`*=` Multiplies the expression on the right to the variable on the left and saves the result in the variable on the left `x *= 3` `x = x * 3`
`/=` Divides the variable on the left by the expression on the right and saves the result in the variable on the left `x /= 3` `x = x / 3`
`%=` Calculates the remainder from dividing variable on the left by the expression on the right and saves the result in the variable on the left `x %= 3` `x = x % 3`

### Increment and Decrement Operators

• Adding or subtracting one is a common operation in programming
• Java provides arithmetic shortcuts for these operations with the increment and decrement operators
• The increment operator (`++`) adds 1 to a variable's value
• Pre-increment adds 1 before evaluating an expression
`++sum;`
• Post-increment evaluates the expression and then adds 1
`sum++;`
• The decrement operator works like the increments operator, except it subtracts 1 from the variable:
```--sum
sum--
```
• Pre- and post- increment matters when the operation is part of a larger expression
• For example, consider the code:
```int x = 5;
int y = x++;
System.out.println("x=" + x + " y=" + y);
```
• We may expect y to be 6 after this code executes
• Instead, y has the value of 5
• The reason is that `++` after a variable (post-increment) is equivalent to:
```y = x;
x = x + 1;
```
• On the other hand, `++` before a variable (pre-increment) is equivalent to:
```x = x + 1;
y = x;
```

### Casting

• We often find ourselves converting one data type into another
• This process is called type conversion or typecasting
• Java is a strongly-typed language and checks for compatible data types both when compiling and while running
• To put a value of a different type in a variable, you must convert the type
• There are two types of conversion: implicit and explicit
• The term for implicit conversion is sometimes called coercion
• The most common form of explicit conversion is know as casting

#### Coercion

• Type conversion is done automatically (implicitly) when a narrower-type is assigned to a broader-type:
• Narrower means a smaller number of bytes
• Broader means a larger number of bytes
• Data type hierarchy (from narrowest to broadest):
```byte => short => int => long => float => double

```
• For example:
```double x;
int n = 5;
x = n;
```
• Since `n` is an integer and `x` is a double, the value returned by `n` must be converted to type `double` before it is assigned to `x`
• Note that casting only changes the type of an expression's returned value
• Not the type of the variable
• Thus the data type of variable `n` is unchanged -- it is still an `int`

#### Coercion in an Arithmetic Expression

• Some arithmetic expressions have a mix of data types
• All values implicitly cast to the highest level before the calculation
• For example:
```double a;
int n = 2;
double y = 1.33;
a = n / y;
```
• `n` is automatically cast to type `double` before performing the arithmetic

#### Explicit Casting

• Explicit casting changes the data type for a single use of the variable
• To cast, precede the variable name with the new data type in parentheses:
```(typeName) variableName
```
• Where:
• typeName: one of the Java data types
• variableName: the name of the variable
• For example:
```int n;
double x = 2.0;
n = (int) x;
```
• The value of `x` is converted from type `double` to `int` before assigning the value to `n`
• Note that explicit casting is required to assign a broader type to a narrower type
• ILLEGAL: Implicit casting to a lower data type:
```int n;
double x = 2.1;
n = x; // illegal in Java
```

Illegal since `x` is `double`, `n` is an `int`, and `double` is a higher data type than `int`

• LEGAL: Explicit casting to a lower data type:
```int n;
double x = 2.1;
n = (int) x; // legal in java
```
• You can use an explicit cast even when an implicit one will be done automatically

#### Truncation When Casting `double` to Integer type

• Converting (casting) a `double` to integer type does not round -- it truncates
• The fractional part is lost (discarded, ignored, thrown away)
• For example:
```int n;
double x = 3.99999;
n = (int) x; // x truncated
```
• Value of `n` is 3

### Introducing Loops

• In your daily life, there are many actions that you repeat until some condition is met.
• For example:
• You might run on the treadmill at the gym until 30 minutes are up.
• You might wash dishes until the pile of dirty dishes is gone.
• You might take classes every quarter until you receive your degree.
• Can you think of any others?
• When we write code, often times we find ourselves repeating statements.
• Loops allow us to carry out repetitive steps in our code without having to re-write the same statements over and over.
• These loops will run until some test condition is met, just like the examples above.
• You wrote your first loops when you did your Hour of Code lab assignment.
• When did you need loops in this assignment?

### Simple Loops

• loop is a block of code that can execute repeatedly
• Whether or not a program repeats a block of code is determined by a test condition
• The test condition is checked each time the loop executes
• In general, loops have three components:
• Initialization code
• Test condition -- evaluated during the loop
• Loop body with some way to change the test condition
• There are three loop statements in Java:
• for
• while
• do...while
• We will start with the simplest of the three -- the `while` statement

While Loops

• The simplest looping structure is the `while` statement
• A `while` statement has a test condition and a body, like an `if` statement
• Before each execution of the loop body, the `while` statement checks the test condition
• If the test condition evaluates to true, then our program executes the body of the loop
• When the program reaches the end of the loop body, it automatically returns to the `while` statement
• Here is the syntax of a while loop:
initialization statement;

while (test)
{

statements to repeat

}
• For example:
String repeat = "y";
while (repeat.equals("y")) {
System.out.print("Do you want to play again? (y/n): ");
repeat = input.next();
}
• What does the while loop syntax remind you of?
• The following flow chart shows how the `while` loop operates

Image source.

### Understanding the `while` Loop

• The following looping application simulates the play of an exciting game
 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 ``` ```import java.util.Scanner;public static void main(String[] args) { Scanner input = new Scanner(System.in);    String repeat = "y"; while (repeat.equals("y")) { System.out.println("\nPlaying an exciting game!"); System.out.print("Do you want to play again? (y/n): "); repeat = input.next(); } System.out.println("\nThanks for playing!"); } ```
• Notice the structure of the code for the looping application
• First was the statement to correctly initialize the looping condition:
`String repeat = "y";`
• Then came the while statement with the test condition
`while (repeat.equals("y"))`
• The loop executes the body of the loop if and only if the condition evaluates to `true`
• Another important part of the loop is the statement:
repeat = input.next();
• Most loops have these parts:
• Initialization code
• Loop test condition
• Loop body with some way to change the test condition
• Question: What would happen if I replaced the while loop with an if statement?
• We will explore the `while` loop more in the next exercise.

### Group Activity: Candy Crush Loop

• As a class, we are going to act out the following while loop:
While Loop :
int num_pieces_candy = 12;
instructor.fill_with_candy(Box, num_pieces_candy);
instructor.hand_box(first_student);
while (num_pieces_candy > 0)
{
student.takeOnePieceCandy();
student.passBox(next_student);
num_pieces_candy--;

}
• With your partner, discuss for the while loop above:
• What is/are the initialization statement(s)?
• What is the loop test condition?
• What are the statements that repeat?
• Which statement will ultimately cause the test condition to fail?
• Now, let's act out the While Loop!

Activity 11.1: Counting Down...
• Grab a partner for pair programming.
• Open up Eclipse and create a new Java project named Countdown.
• Imagine we are at NASA Mission Control.
• A new space ship is about to be launched.
• Let's write a program that counts down until take off. See the sample output below:
NASA Mission Control readying for liftoff.
Initializing countdown from 10...
10
9
8
7
6
5
4
3
2
1
We have liftoff!
• We are going to write this program in two ways.

Part 1: Repetition, Repetition, Repetition (10 pts)
• The first program should use 13 System.out statements to achieve the above output.
• Declare an integer variable called countdown at the top of main and set it equal to 10.
• Now, write a System.out statement to output the following:
NASA Mission Control readying for liftoff.
• Add another System.out statement to print the following to the console:
Initializing countdown from 10...
• Next, in a pair of statements, lets print the contents of countdown and then decrease its value by 1.
System.out.println(countdown);
countdown--;
• You will need to repeat these two lines of code 10 times in your program.
• Copy the two lines and then paste them into your program 9 more times.
• You should have a very repetitive program by now!
• Finally, add a System.out statement to print out "We have liftoff!" below the numbers.
• Run your code to make sure that your output is identical to my output above.
• When you are finished and the program is working properly, upload it to Canvas.

Part 2: Using a While Loop (10 pts)
• Let's alter the above program to be written more efficiently with a loop.
• First, take a look at your code.
• Which part of the code is repetitive?
• Hint: The repetitive lines will go inside the while loop.
• We need a while loop to count down from the number entered by the user. Create a while loop that looks like this:
while (test will go here) {
//statements
}
• What should go inside the test?
countdown > 0
• Why do you use > 0 here?
• Inside the curly braces of the while loop, we need to print out the contents of the countdown variable and then decrease its value by 1.
• Take one of your pairs of System.out statement and variable decrement and place it in the curly braces of the while loop.
• Now, you can erase the other 9 pairs of statements.
• Finally, below your while loop, there should now be only one System.out statement
• Run your program to make sure it is working the same as before.
• When you are finished, upload this new version to Canvas.

• Like the `if`-statement, the curly braces of a `while` loop are optional
• Technically, the `while` statement affects only the single statement that follows
• We use curly braces to make that one statement into a block of statements
• This allows us to put any number of statements within the body
• Curly braces are not always required, but the best practice is to always include them

#### Program Style: Indent Statements Inside a Loop

• It is important to format the loop code correctly:
```String repeat = "y";
while (repeat.equals("y")) {
// ... statements to repeat
repeat = input.next();
}```
Also Accepted Style:
String repeat = "y";
while (repeat.equals("y"))
{
// ... statements to repeat
repeat = input.next();
}
• Note how the repeated code is indented inside the loop
• This lets us see easily which code is repeated and which is not
• Also note the placement of curly braces
• Different groups have different practices for placing curly braces in a loop statement

## Applications of While Loops

• Let's look at 4 common loop applications:

### Indefinite Loops

• An indefinite loop is one where you don't know when the loop will end.
• The loop will end (unlike an infinite loop), but you, the programmer, cannot predict exactly how many times it will run (unlike a counting loop)
• Instead, it is usually up to the user to decide when to end the loop by pressing a particular key
• Recall the example looping application that simulated the play of an exciting game

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y")){
System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");
repeat = input.next();
}
System.out.println("\nThanks for playing!");
}

• Loops of this type are called indefinite loops because you do not know in advance how many time the loop will execute
• This behavior is different from a counting loop where you know how many times the loop will execute before the loop starts
• With an indefinite loop we can solve a new set of problems
• Most problems solved with indefinite loops make use of while statements

### Processing a Sequence of Inputs

• Another common use for indefinite loops is to process a sequence of inputs
• As an example, let us add up (sum) a series of numbers
• Every number is added to the sum
• We use a loop to repeat the input until the user decides to stop
• Since we do not know how many number the user will enter, we use an indefinite loop as shown below
image source

#### Program Processing a Sequence of Numerical Inputs

public static void main(String[] args) {
double number = 1;
double sum = 0;
String repeat = "y";
Scanner input = new Scanner(System.in);
System.out.println("I will add up numbers for you\n");

while (repeat.equals("y")) {
System.out.println("So far, sum = " + sum);
System.out.print("Enter a number: ");
number = input.nextDouble();
sum = sum + number;
System.out.print("Another number? (y/n) ");
repeat = input.next();
}

System.out.println("Ending sum: " + sum);
}

### Terminating the Input with a Sentinel

Whenever we read a sequence of input values, we need to have some way of terminating the input loop
We could use a separate variable and input statement as we have done before:

String repeat = "y";
while (repeat.equals("y")) {
// ... statements to repeat
repeat = input.next();
}

• However, when entering numbers (or other data) repeatedly, answering an extra question each time through the loop becomes annoying
• One way to avoid asking an extra question is to use a sentinel value
• A sentinel is guard who watches for something to happen
• Similarly, a sentinel in a program watches for a specific sentinel value that signals termination of a loop
• To use a sentinel value, we must have a special value in the input
• Some commonly used sentinel values for numeric input are 0 or -1
• However, if our application suggests another value, then we should use that value
• The following program is an update of the previous program to use a sentinel value to end the loop

#### Example Application Using a Sentinel Value for the Loop Test

public static void main(String[] args) {
double number = 1;
double sum = 0;
Scanner input = new Scanner(System.in);
System.out.println("I will add up numbers for you\n");
while (number != 0) {
System.out.println("So far, sum = " + sum);
System.out.print("Enter a number or 0 to exit: ");
number = input.nextDouble(); sum = sum + number;
}
System.out.println("\nEnding sum: " + sum);
}

### Input Validation

• Another common use for indefinite loops is input validation
• Input validation combines a loop with one or more if statements
• The input statement is placed inside the loop
• The if-statement tests for an incorrect input value
• The loop repeats while the user's input contains an error
• Since we do not know how many times the loop must execute ahead of time, the loop is indefinite
• For example, the following program uses a loop to ensure a user enters a positive number
• The if statement is used to decide when to output an error message
• Example of Input Validation Using a Loop

public static void main(String[] args) {
double number = 0.0; // initialize value
Scanner input = new Scanner(System.in);

while (number <= 0) { System.out.print("Enter a positive number: ");
number = input.nextDouble();
if (number <= 0.0) {
System.out.println("You must enter a positive number\n");
}
}
System.out.println("\nYou entered: " + number);
}

We will explore all of these applications in our programs as we continue to write loops.

### Activity 11.2: Guessing Game The Final Round (10 pts)

• Find a partner for pair programming
• Copy the following program into an Eclipse project named Loopy and then compile and run the starter program to make sure you copied it correctly.

import java.util.Scanner;
public class Loopy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int guess = 0;
System.out.print("I'm thinking of a number between"
+ " 1 and 10.\nCan you guess it?\n\n"
guess = input.nextInt();

if (7 == guess) {
System.out.println("*** Correct! ***\n");
} else {
System.out.println("Sorry, that is not correct.");
System.out.println("Try again.");
}
}
}

• Add the following code after the statement where int guess is declared:
String repeat = "y";

• This is the initialization code that we will use for the test condition that comes next.
• We want to repeat all the rest of the code in our program.
• For this we need to add a while statement such as:
while (repeat.equalsIgnoreCase("y")) {
// Place the code after the initialization statements
// and before the end of main between these curly braces.
}
• Statements inside the curly braces repeat while the test condition in the parenthesis, (repeat.equalsIgnoreCase("y")), evaluates to true.
• Inside the while loop we need some way to change the test condition.
• We change the test condition by letting the user enter a value for the repeat variable by adding the following code at the end of the loop just before the closing curly brace:
System.out.print("\nDo you want to play again? (y/n) ");
repeat = input.next();

• Without these two statements our loop would have no way to exit. A loop with no way to exit is known as an infinite loop.
• Formatting a loop is important. Indent all the code within the curly braces of the while loop.
• As a final part of our program, we add the infamous phrase: "Game Over".
• Add the following statement after the closing curly brace of the while loop:
System.out.println("Game over");
• Compile and run your program again and verify the output looks like:

I'm thinking of a number between 1 and 10.
Can you guess it?

Sorry, that is not correct. Try again.
Do you want to play again? (y/n) y
I'm thinking of a number between 1 and 10.
Can you guess it?

*** Correct! ***
Do you want to play again? (y/n) n
Game over

• Submit your program source code to Canvas.
• If you finish early, find someone to help! Remember, you learn by teaching others.

Completed Program

• When finished, your application should look like the following.
• Note especially the extra indentation within the curly braces of the while loop and the if-else statements.

## Common Loop Pitfalls

• Loops have many pitfalls for the unwary
• The following are the most common problems you should look out for

### Infinite Loops

• Common error: unintentional infinite loop
• For example, what is wrong with the following code?

public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y")) {
System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");
}
System.out.println("\nThanks for playing!");
}

### Missing Curly Braces

• The curly braces of a while loop let us associate multiple statements with a while loop
• However, if we leave off the curly braces, only the first line of code after the while statement is interpreted to be part of the loop.
• For example, what is wrong with the following code?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y"))
System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");
repeat = input.next();

System.out.println("\nThanks for playing!");
}

### Empty Statements

• Remember that statements are terminated by a semicolon
• Is the following a legal statement?;
• This is known as an empty or null statement
• Empty statements are a common source of infinite loops
• For example, what is wrong with the following code?
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String repeat = "y";
while (repeat.equals("y")) ;
System.out.println("\nPlaying an exciting game!");
System.out.println("Do you want to play again? (y/n) ");
repeat = input.next();
System.out.println("\nThanks for playing!");
}
}