> ## Documentation Index
> Fetch the complete documentation index at: https://v1-learn.neoartd.my.id/llms.txt
> Use this file to discover all available pages before exploring further.

# While Loops

> 12 assignments

## 48. Enter Your PIN - [Link](https://programmingbydoing.com/a/enter-pin.html)

<Tabs>
  <Tab title="Task">
    Type in the following code, and get it to compile. This assignment will help you learn how to make a loop, so that you can repeat a section of code over and over again!

    **Sample Output**

    ```bash theme={null}
    WELCOME TO THE BANK OF MITCHELL.
    ENTER YOUR PIN: 90210

    INCORRECT PIN. TRY AGAIN.
    ENTER YOUR PIN: 11111

    INCORRECT PIN. TRY AGAIN.
    ENTER YOUR PIN: 12345

    PIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.
    ```

    Notice what happens when we type the correct PIN on the first try:

    ```bash theme={null}
    WELCOME TO THE BANK OF MITCHELL.
    ENTER YOUR PIN: 12345

    PIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.
    ```
  </Tab>

  <Tab title="Answer">
    ```java EnterPIN.java theme={null}
    import java.util.Scanner;

    public class EnterPIN
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            int pin = 12345;

            System.out.println("WELCOME TO THE BANK OF MITCHELL.");
            System.out.print("ENTER YOUR PIN: ");
            int entry = keyboard.nextInt();

            while ( entry != pin )
            {
                System.out.println("\nINCORRECT PIN. TRY AGAIN.");
                System.out.print("ENTER YOUR PIN: ");
                entry = keyboard.nextInt();
            }

            System.out.println("\nPIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.");
        }
    }
    ```
  </Tab>

  <Tab title="Question">
    Assignments turned in *without* these things will not receive any points.

    1. How is a `while` loop similar to an `if` statement?
       > Answer: They both check a condition and execute the code block if the condition is true.
    2. How is a while loop different from an if statement?
       > Answer: A while loop will keep executing the code block as long as the condition is true, while an if statement will only execute the code block once if the condition is true.
    3. Inside the while loop, why isn't there an int in front of the line entry = keyboard.nextInt()?
       > Answer: Because the variable `entry` has been declared before the while loop.
    4. Delete the line entry = keyboard.nextInt(); from inside the while loop. What happens? Why?
       > Answer: The program will not ask for the PIN again if the PIN is incorrect. This is because the program will not update the value of the `entry` variable.
    5. (Put the entry = keyboard.nextInt(); back before you turn in the assignment.)
  </Tab>
</Tabs>

## 49. Keep Guessing - [Link](https://programmingbydoing.com/a/keep-guessing.html)

<Tabs>
  <Tab title="Task">
    Modify your previous [number-guessing game](https://programmingbydoing.com/a/a-number-guessing-game.html) so that they can guess **until** they get it right. That means it will keep looping as long as the guess is different from the secret number. Use a `while` loop.

    **Sample Output**

    ```bash theme={null}
    I have chosen a number between 1 and 10. Try to guess it.
    Your guess: 5
    That is incorrect. Guess again.
    Your guess: 4
    That is incorrect. Guess again.
    Your guess: 8
    That is incorrect. Guess again.
    Your guess: 6
    That's right! You're a good guesser.
    ```
  </Tab>

  <Tab title="Answer">
    ```java KeepGuessing.java theme={null}
    import java.util.Random;
    import java.util.Scanner;

    public class KeepGuessing
    {
        public static void main( String[] args )
        {
            Random r = new Random();
            Scanner keyboard = new Scanner(System.in);
            int number = 1 + r.nextInt(10);
            int guess;

            System.out.println("I have chosen a number between 1 and 10. Try to guess it.");
            System.out.print("Your guess: ");
            guess = keyboard.nextInt();

            while ( guess != number )
            {
                System.out.println("That is incorrect. Guess again.");
                System.out.print("Your guess: ");
                guess = keyboard.nextInt();
            }

            System.out.println("That's right! You're a good guesser.");
        }
    }
    ```
  </Tab>
</Tabs>

## 50. Dice Doubles - [Link](https://programmingbydoing.com/a/dice-doubles.html)

<Tabs>
  <Tab title="Task">
    Modify your [dice game](https://programmingbydoing.com/a/dice.html) from last time so that it keeps rolling until they get doubles (the same number on both dice).

    Notice that since there's no user input, this will happen very quickly (all the rolls will happen one right after the other).

    **Sample Output**

    ```bash theme={null}
    HERE COMES THE DICE!

    Roll #1: 3
    Roll #2: 5
    The total is 8!

    Roll #1: 6
    Roll #2: 1
    The total is 7!

    Roll #1: 2
    Roll #2: 5
    The total is 7!

    Roll #1: 1
    Roll #2: 1
    The total is 2!
    ```
  </Tab>

  <Tab title="Answer">
    ```java DiceDoubles.java theme={null}
    import java.util.Random;

    public class DiceDoubles
    {
        public static void main( String[] args )
        {
            Random r = new Random();

            int roll1 = 1 + r.nextInt(6);
            int roll2 = 1 + r.nextInt(6);

            System.out.println("HERE COMES THE DICE!\n");

            while ( roll1 != roll2 )
            {
                System.out.printf("Roll #1: %s\n", roll1);
                System.out.printf("Roll #2: %s\n", roll2);
                System.out.printf("The total is %s!\n\n", roll1 + roll2);

                roll1 = 1 + r.nextInt(6);
                roll2 = 1 + r.nextInt(6);
            }

            System.out.printf("Roll #1: %s\n", roll1);
            System.out.printf("Roll #2: %s\n", roll2);
            System.out.printf("The total is %s!\n", roll1 + roll2);
        }
    }
    ```
  </Tab>
</Tabs>

## 51. Counting with a While Loop - [Link](https://programmingbydoing.com/a/counting-while.html)

<Tabs>
  <Tab title="Task">
    Type in the following code, and get it to compile. This assignment shows you how we can abuse a `while` loop to make something repeat an exact number of times.

    Normally, while loops are best for repeating as long as something is true:

    * Keep going as long as they haven't guessed it.
    * Keep going as long as you haven't got doubles.
    * Keep going as long as they keep typing in a negative number.
    * Keep going as long as they haven't typed in a zero.

    But sometimes, we know in advance how many times we want to do something.

    * Do this ten times.
    * Do this five times.
    * Pick a random number, and do it that many times.
    * Take this list of items, and do it one time for each item in the list.

    We can do that sort of thing with a `while` loop, but we have to use a counter. A counter is a number variable (`int` or `double`) that starts with a value of 0, and then we add 1 to it whenever something happens. So, here, we're going to be adding 1 to the counter everytime we repeat the loop. And when the counter reaches a predetermined value, we'll stop looping.

    **Sample Output**

    ```bash theme={null}
    Type in a message, and I'll display it five times.
    Message: All work and no play makes Jack a dull boy.
    1. All work and no play makes Jack a dull boy.
    2. All work and no play makes Jack a dull boy.
    3. All work and no play makes Jack a dull boy.
    4. All work and no play makes Jack a dull boy.
    5. All work and no play makes Jack a dull boy.
    ```
  </Tab>

  <Tab title="Answer">
    ```java CountingWhile.java theme={null}
    import java.util.Scanner;

    public class CountingWhile
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);

            System.out.println( "Type in a message, and I'll display it five times." );
            System.out.print( "Message: " );
            String message = keyboard.nextLine();

            int n = 0;
            while ( n < 5 )
            {
                System.out.println( (n+1) + ". " + message );
                n++;
            }

        }
    }
    ```
  </Tab>

  <Tab title="Question">
    Assignments turned in *without* these things will not receive any points.

    1. What does `n++` do? Remove it and see what happens. (Then put it back.)
       > Answer: `n++` increments the value of the `n` variable by 1. If it is removed, the program will keep printing the message indefinitely.
    2. Change the code so that the loop repeats ten times instead of five.
       > Answer: Change the condition of the while loop to `n < 10`.
    3. See if you can change the code so that the message still prints ten times, but the numbers in front count by tens, like so:
       ```bash theme={null}
       Type in a message, and I'll display it ten times.
       Message: I'm sending out an S.O.S.
       10. I'm sending out an S.O.S.
       20. I'm sending out an S.O.S.
       30. I'm sending out an S.O.S.
       40. I'm sending out an S.O.S.
       50. I'm sending out an S.O.S.
       60. I'm sending out an S.O.S.
       70. I'm sending out an S.O.S.
       80. I'm sending out an S.O.S.
       90. I'm sending out an S.O.S.
       100. I'm sending out an S.O.S.
       ```
       > Answer: Change the `System.out.println( (n+1) + ". " + message );` line to `System.out.println( (n+1) * 10 + ". " + message );`.
    4. Change the code so that it asks the person how many times to display the message. Then, print it that many times. Still count by tens.
       ```bash theme={null}
       Type in a message, and I'll display it several times.
       Message: HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
       How many times? 3
       10. HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
       20. HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
       30. HELLO! My name is Inigo Montoya. You killed my father; prepare to die.
       ```
       > Answer: Add a new variable to store the number of times the message will be displayed. Then, change the condition of the while loop to `n < times`.
  </Tab>
</Tabs>

## 52. PIN Lockout - [Link](https://programmingbydoing.com/a/pin-lockout.html)

<Tabs>
  <Tab title="Task">
    This assignment will help you learn how to make a loop, so that you can repeat a section of code over and over again!

    **Sample Output**

    ```bash theme={null}
    WELCOME TO THE BANK OF MITCHELL.
    ENTER YOUR PIN: 10101

    INCORRECT PIN. TRY AGAIN.
    ENTER YOUR PIN: 23232

    INCORRECT PIN. TRY AGAIN.
    ENTER YOUR PIN: 99999

    YOU HAVE RUN OUT OF TRIES. ACCOUNT LOCKED.
    ```
  </Tab>

  <Tab title="Answer">
    Type in the following code, and get it to compile.

    ```java PinLockout.java theme={null}
    import java.util.Scanner;

    public class PinLockout
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            int pin = 12345;
            int tries = 0;

            System.out.println("WELCOME TO THE BANK OF MITCHELL.");
            System.out.print("ENTER YOUR PIN: ");
            int entry = keyboard.nextInt();
            tries++;

            while ( entry != pin && tries < 3 )
            {
                System.out.println("\nINCORRECT PIN. TRY AGAIN.");
                System.out.print("ENTER YOUR PIN: ");
                entry = keyboard.nextInt();
                tries++;
            }

            if ( entry == pin )
                System.out.println("\nPIN ACCEPTED. YOU NOW HAVE ACCESS TO YOUR ACCOUNT.");
            else if ( tries >= 3 )
                System.out.println("\nYOU HAVE RUN OUT OF TRIES. ACCOUNT LOCKED.");
        }
    }
    ```
  </Tab>

  <Tab title="Question">
    Assignments turned in *without* these things will not receive any points.

    1. Change the code so that it locks them out after 4 tries instead of 3. Make sure to change the message at the bottom, too.
       > Answer: Change the condition of the while loop to `tries < 4` and the message at the bottom to `else if ( tries >= 4 )`.
    2. Move the "maximum tries" value into a variable, and use that variable everywhere instead of just the number.
       > Answer: Add a new variable to store the maximum number of tries and use it in the condition of the while loop and the message at the bottom.
       ```java theme={null}
       int maxTries = 4;
       while ( entry != pin && tries < maxTries )
       ...
       else if ( tries >= maxTries )
       ```
  </Tab>
</Tabs>

## 53. Number-Guessing with a Counter - [Link](https://programmingbydoing.com/a/number-guessing-with-a-counter.html)

<Tabs>
  <Tab title="Task">
    Modify your previous [number-guessing game](https://programmingbydoing.com/a/keep-guessing.html) so that they can guess until they get it right **AND** count the number of tries it takes them to guess it.

    **Sample Output**

    ```bash theme={null}
    I have chosen a number between 1 and 10.  Try to guess it.
    Your guess: 5
    That is incorrect.  Guess again.
    Your guess: 4
    That is incorrect.  Guess again.
    Your guess: 8
    That is incorrect.  Guess again.
    Your guess: 6
    That's right!  You're a good guesser.
    It only took you 4 tries.
    ```
  </Tab>

  <Tab title="Answer">
    ```java NumberGuessingWithCounter.java theme={null}
    import java.util.Random;
    import java.util.Scanner;

    public class NumberGuessingWithCounter
    {
        public static void main( String[] args )
        {
            Random r = new Random();
            Scanner keyboard = new Scanner(System.in);
            int number = 1 + r.nextInt(10);
            int guess;
            int tries = 0;

            System.out.println("I have chosen a number between 1 and 10. Try to guess it.");
            System.out.print("Your guess: ");
            guess = keyboard.nextInt();
            tries++;

            while ( guess != number )
            {
                System.out.println("That is incorrect. Guess again.");
                System.out.print("Your guess: ");
                guess = keyboard.nextInt();
                tries++;
            }

            System.out.println("That's right! You're a good guesser.");
            System.out.printf("It only took you %s tries.\n", tries);
        }
    }
    ```
  </Tab>
</Tabs>

## 54. Hi-Lo with Limited Tries - [Link](https://programmingbydoing.com/a/hi-lo-with-limited-tries.html)

<Tabs>
  <Tab title="Task">
    Write a program that picks a random number from 1-100. The user keeps guessing as long as their guess is wrong, **and** they've guessed less than 7 times. If their guess is higher than the number, say "Too high." If their guess is lower than the number, say "Too low." When they get it right, the game stops. Or, if they hit seven guesses, the game stops even if they never got it right.

    This means your `while` loop will have a compound condition using &&.

    **Sample Output**

    ```bash theme={null}
    I'm thinking of a number between 1-100.  You have 7 guesses.
    First guess: 50
    Sorry, you are too low.
    Guess # 2: 75
    Sorry, you are too low.
    Guess # 3: 87
    Sorry, that guess is too high.
    Guess # 4: 82
    Sorry, you are too low.
    Guess # 5: 84
    You guessed it!  What are the odds?!?
    ```

    ```bash theme={null}
    I'm thinking of a number between 1-100.  You have 7 guesses.
    First guess: 1
    Sorry, you are too low.
    Guess # 2: 2
    Sorry, you are too low.
    Guess # 3: -8
    Sorry, you are too low.
    Guess # 4: 0
    Sorry, you are too low.
    Guess # 5: 7
    Sorry, you are too low.
    Guess # 6: 612
    Sorry, that guess is too high.
    Guess # 7: -523
    Sorry, you didn't guess it in 7 tries.  You lose.
    ```
  </Tab>

  <Tab title="Answer">
    ```java HiLoLimited.java theme={null}
    import java.util.Random;
    import java.util.Scanner;

    public class HiLoLimited
    {
        public static void main( String[] args )
        {
            Random r = new Random();
            Scanner keyboard = new Scanner(System.in);
            int number = 1 + r.nextInt(100);
            int guess;
            int tries = 1;

            System.out.println("I'm thinking of a number between 1-100. You have 7 guesses.");

            System.out.print("First guess: ");
            guess = keyboard.nextInt();

            while ( guess != number && tries < 7 )
            {
                if ( guess < number )
                    System.out.println("Sorry, you are too low.");
                if ( guess > number )
                    System.out.println("Sorry, that guess is too high.");

                System.out.printf("Guess #%s: ", tries + 1);
                guess = keyboard.nextInt();
                tries++;
            }

            if ( guess == number )
                System.out.println("You guessed it! What are the odds?!?");
            else
                System.out.println("Sorry, you didn't guess it in 7 tries. You lose.");
        }
    }
    ```
  </Tab>
</Tabs>

## 55. Adding Values in a Loop - [Link](https://programmingbydoing.com/a/adding-values-in-a-loop.html)

<Tabs>
  <Tab title="Task">
    Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.

    You must use a `while` loop.

    **Sample Output**

    ```bash theme={null}
    I will add up the numbers you give me.
    Number: 6
    The total so far is 6
    Number: 9
    The total so far is 15
    Number: -3
    The total so far is 12
    Number: 2
    The total so far is 14
    Number: 0

    The total is 14.
    ```

    ```bash theme={null}
    I will add up the numbers you give me.
    Number: 1
    The total so far is 1
    Number: 2
    The total so far is 3
    Number: 3
    The total so far is 6
    Number: 4
    The total so far is 10
    Number: 5
    The total so far is 15
    Number: 0

    The total is 15
    ```
  </Tab>

  <Tab title="Answer">
    ```java AddingValuesInALoop.java theme={null}
    import java.util.Scanner;

    public class AddingValuesInALoop
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            int number;
            int total = 0;

            System.out.println("I will add up the numbers you give me.");

            System.out.print("Number: ");
            number = keyboard.nextInt();
            total += number;
            System.out.printf("The total so far is %s", total);

            while ( number != 0 )
            {
                System.out.print("Number: ");
                number = keyboard.nextInt();
                total += number;
                if (number != 0){
                    System.out.printf("The total so far is %s", total);
                } else {
                    System.out.printf("\nThe total is %s", total);
                }
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 60. Safe Square Root - [Link](https://programmingbydoing.com/a/safe-square-root.html)

<Tabs>
  <Tab title="Task">
    Write a program to take the square root of a number typed in by the user. Your program should use a loop to ensure that the number they typed in is positive. If the number is negative, you should print out some sort of warning and make them type it in again.

    Note that it is possible to do this program with either a `while` loop or a `do-while` loop. (Though personally, I think this one is easier with a `while` loop.)

    You can get the square root of a number n with `Math.sqrt(n)`. Make sure you don't do this until the loop is done and you know for sure you've got a positive number.

    **Sample Output**

    ```bash theme={null}
    SQUARE ROOT!
    Enter a number: 9
    The square root of 9 is 3.0.
    ```

    ```bash theme={null}
    SQUARE ROOT!
    Enter a number: 2
    The square root of 2 is 1.4142135623730951.
    ```

    ```bash theme={null}
    SQUARE ROOT!
    Enter a number: -9
    You can't take the square root of a negative number, silly.
    Try again: -10
    You can't take the square root of a negative number, silly.
    Try again: 10
    The square root of 10 is 3.1622776601683795.
    ```
  </Tab>

  <Tab title="Answer">
    ```java SafeSquareRoot.java theme={null}
    import java.util.Scanner;

    public class SafeSquareRoot
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            double number;

            System.out.println("SQUARE ROOT!");
            System.out.print("Enter a number: ");
            number = keyboard.nextDouble();

            while ( number < 0 )
            {
                System.out.println("You can't take the square root of a negative number, silly.");
                System.out.print("Try again: ");
                number = keyboard.nextDouble();
            }

            System.out.printf("The square root of %s is %s.\n", number, Math.sqrt(number));
        }
    }
    ```
  </Tab>
</Tabs>

## 61. Right Triangle Checker - [Link](https://programmingbydoing.com/a/right-triangle-checker.html)

<Tabs>
  <Tab title="Task">
    Write a program to allow the user to enter three integers. You must use `do-while` or `while` loops to enforce that these integers are in ascending order, though duplicate numbers are allowed.

    Tell the user whether or not these integers would represent the sides of a right triangle.

    **Sample Output**

    ```bash theme={null}
    Enter three integers:
    Side 1: 4
    Side 2: 3
    3 is smaller than 4.  Try again.
    Side 2: -9
    -9 is smaller than 4.  Try again.
    Side 2: 5
    Side 3: 1
    1 is smaller than 5.  Try again.
    Side 3: 5

    Your three sides are 4 5 5
    NO!  These sides do not make a right triangle!
    ```

    ```bash theme={null}
    Enter three integers:
    Side 1: 6
    Side 2: 8
    Side 3: 10

    Your three sides are 6 8 10
    These sides *do* make a right triangle.  Yippy-skippy!
    ```
  </Tab>

  <Tab title="Answer">
    ```java RightTriangleChecker.java theme={null}
    import java.util.Scanner;

    public class RightTriangleChecker
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            int side1, side2 = 0, side3 = 0;
            int stop = 2;

            System.out.println("Enter three integers:");
            System.out.print("Side 1: ");
            side1 = keyboard.nextInt();

            while ( stop <= 3 )
            {
                System.out.printf("\nSide %s: ", stop);
                if ( stop == 2 )
                {
                    side2 = keyboard.nextInt();
                    while ( side2 < side1 )
                    {
                        System.out.printf("%s is smaller than %s. Try again.\n", side2, side1);
                        System.out.printf("Side %s: ", stop);
                        side2 = keyboard.nextInt();
                    }
                }
                else if ( stop == 3 )
                {
                    side3 = keyboard.nextInt();
                    while ( side3 < side2 )
                    {
                        System.out.printf("%s is smaller than %s. Try again.\n", side3, side2);
                        System.out.printf("Side %s: ", stop);
                        side3 = keyboard.nextInt();
                    }
                }
                stop++;
            }

            System.out.printf("\nYour three sides are %s %s %s\n", side1, side2, side3);

            if ( Math.pow(side1, 2) + Math.pow(side2, 2) == Math.pow(side3, 2) )
                System.out.println("These sides *do* make a right triangle.  Yippy-skippy!");
            else
                System.out.println("NO!  These sides do not make a right triangle!");
        }
    }
    ```
  </Tab>
</Tabs>

## 62. Collatz Sequence - [Link](https://programmingbydoing.com/a/collatz-sequence.html)

<Tabs>
  <Tab title="Task">
    Take any natural number n.

    * If n is even, divide it by 2 to get n / 2.
    * If n is odd, multiply it by 3 and add 1 to get 3n + 1.
    * Repeat the process indefinitely.

    In 1937, Lothar Collatz proposed that no matter what number you begin with, the sequence eventually reaches 1. This is widely believed to be true, but has never been formally proved.

    Write a program that inputs a number from the user, and then displays the Collatz Sequence starting from that number. Stop when you reach 1.

    **Sample Output**
    Here's an example of the expected output, assuming I start with 6 and print tabs between each number.

    ```bash theme={null}
    Starting number: 6
    6     3      10     5      16     8      4      2     1
    ```

    Or, starting with a different number:

    ```bash theme={null}
    Starting number: 11
    11    34    17    52    26    13    40    20    10    5
    16    8     4     2     1
    ```

    Some numbers take quite a while to reach 1:

    ```bash theme={null}
    Starting number: 27
    27    82    41    124   62    31    94    47    142   71
    214   107   322   161   484   242   121   364   182   91
    274   137   412   206   103   310   155   466   233   700
    350   175   526   263   790   395   1186  593   1780  890
    445   1336  668   334   167   502   251   754   377   1132
    566   283   850   425   1276  638   319   958   479   1438
    719   2158  1079  3238  1619  4858  2429  7288  3644  1822
    911   2734  1367  4102  2051  6154  3077  9232  4616  2308
    1154  577   1732  866   433   1300  650   325   976   488
    244   122   61    184   92    46    23    70    35    106
    53    160   80    40    20    10    5     16    8     4
    2     1
    ```
  </Tab>

  <Tab title="Answer">
    ```java CollatzSequence.java theme={null}
    import java.util.Scanner;

    public class CollatzSequence
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            int number;

            System.out.print("Starting number: ");
            number = keyboard.nextInt();

            System.out.printf("%s\t", number);
            while ( number != 1 )
            {
                if ( number % 2 == 0 )
                    number /= 2;
                else
                    number = 3 * number + 1;

                System.out.printf("%s\t", number);
            }
        }
    }
    ```
  </Tab>

  <Tab title="Bonus">
    * **Bonus #1 - Count Steps**
      For +10 bonus points, also display the total number of steps in the sequence.
      ```bash theme={null}
      Starting number: 11
      11    34    17    52    26    13    40    20    10    5
      16    8     4     2     1

      Terminated after 14 steps.
      ```
      ```bash theme={null}
      Starting number: 27
      27    82    41    124   62    31    94    47    142   71
      214   107   322   161   484   242   121   364   182   91
      274   137   412   206   103   310   155   466   233   700
      350   175   526   263   790   395   1186  593   1780  890
      445   1336  668   334   167   502   251   754   377   1132
      566   283   850   425   1276  638   319   958   479   1438
      719   2158  1079  3238  1619  4858  2429  7288  3644  1822
      911   2734  1367  4102  2051  6154  3077  9232  4616  2308
      1154  577   1732  866   433   1300  650   325   976   488
      244   122   61    184   92    46    23    70    35    106
      53    160   80    40    20    10    5     16    8     4
      2     1

      Terminated after 111 steps.
      ```
      > Answer: Add a new variable to store the number of steps and increment it every time the number is updated.
      ```java theme={null}
      int steps = 0;
      while ( number != 1 )
      {
          if ( number % 2 == 0 )
              number /= 2;
          else
              number = 3 * number + 1;

          System.out.printf("%s\t", number);
          steps++;
      }
      System.out.printf("\n\nTerminated after %s steps.\n", steps);
      ```

    * **Bonus #2 - Largest Value**
      For +20 bonus points, display the largest value encounted in the sequence.
      ```bash theme={null}
      Starting number: 11
      11    34    17    52    26    13    40    20    10    5
      16    8     4     2     1

      The largest value was 52.
      ```
      ```bash theme={null}
      Starting number: 27
      27    82    41    124   62    31    94    47    142   71
      214   107   322   161   484   242   121   364   182   91
      274   137   412   206   103   310   155   466   233   700
      350   175   526   263   790   395   1186  593   1780  890
      445   1336  668   334   167   502   251   754   377   1132
      566   283   850   425   1276  638   319   958   479   1438
      719   2158  1079  3238  1619  4858  2429  7288  3644  1822
      911   2734  1367  4102  2051  6154  3077  9232  4616  2308
      1154  577   1732  866   433   1300  650   325   976   488
      244   122   61    184   92    46    23    70    35    106
      53    160   80    40    20    10    5     16    8     4
      2     1

      The largest value was 9232.
      ```
      > Answer: Add a new variable to store the largest value and update it every time the number is updated.
      ```java theme={null}
      int large = 0;
      while ( number != 1 )
      {
          large = Math.max(large, number);
          if ( number % 2 == 0 )
              number /= 2;
          else
              number = 3 * number + 1;

          System.out.printf("%s\t", number);
          steps++;
      }
      System.out.printf("\n\nThe largest value was %s.\n", large);
      ```

    * **Bonus #3 - Both**
      For +30 bonus points, do both.
      ```bash theme={null}
      Starting number: 11
      11    34    17    52    26    13    40    20    10    5
      16    8     4     2     1

      Terminated after 14 steps. The largest value was 52.
      ```
      > Answer: Combine both bonus #1 and bonus #2.
      ```java theme={null}
      int steps = 0;
      int large = 0;
      while ( number != 1 )
      {
          large = Math.max(large, number);
          if ( number % 2 == 0 )
              number /= 2;
          else
              number = 3 * number + 1;

          System.out.printf("%s\t", number);
          steps++;
      }

      System.out.printf("\n\nTerminated after %s steps. The largest value was %s.\n", steps, large);
      ```
  </Tab>
</Tabs>

## 63. Short Adventure 2: With a Loop - [Link](https://programmingbydoing.com/a/adventure2.html)

<Tabs>
  <Tab title="Task">
    Make another short "Choose Your Own Adventure" game. However, this time you need to use a loop so that they can freely move from room to room and back again.

    There need to be at least six rooms or destinations, and at least two different ways for the game to end.

    **Files Needed**

    * [Adventure2.java](https://programmingbydoing.com/a/examples/Adventure2.java) - empty shell
    * [Adventure2Example.java](https://programmingbydoing.com/a/examples/Adventure2Example.java) - tiny sample game

    **Sample Output**

    ```bash theme={null}
    MITCHELL'S TINY ADVENTURE 2!

    You are in a creepy house!  Would you like to go "upstairs" or into the
    "kitchen"?
    > kitchen

    There is a long countertop with dirty dishes everywhere.  Off to one side
    there is, as you'd expect, a refrigerator.  You may open the "refrigerator"
    or go "back".
    > back

    You are in a creepy house!  Would you like to go "upstairs" or into the
    "kitchen"?
    > upstairs

    Upstairs you see a hallway.  At the end of the hallway is the master
    "bedroom".  There is also a "bathroom" off the hallway.  Or, you can
    go back "downstairs". Where would you like to go?
    > downstairs

    You are in a creepy house!  Would you like to go "upstairs" or into the
    "kitchen"?
    > kitchen

    There is a long countertop with dirty dishes everywhere.  Off to one side
    there is, as you'd expect, a refrigerator.  You may open the "refrigerator"
    or go "back".
    > refrigerator

    Inside the refrigerator you see food and stuff.  It looks pretty nasty.
    Would you like to eat some of the food? ("yes" or "no")
    > yes

    The food is slimy and foul, but you manage to choke it down. Your stomach
    starts jumping like a frog in hot water.  You feel faint. Sliding to the
    floor, the darkness closes in.

    You have died.
    ```
  </Tab>

  <Tab title="Answer">
    ```java Adventure2.java theme={null}
    import java.util.Scanner;

    public class Adventure2
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);

            int nextroom = 1;
            String choice = "";

            while ( nextroom != 0 )
            {
                if ( nextroom == 1 )
                {
                    System.out.println( "Kamu saat ini di halaman sekarang mau kemana? \"ruang tamu\" / \"keluar\"" );
                    System.out.print( "> " );
                    choice = keyboard.nextLine();
                    if ( choice.equals("ruang tamu") )
                        nextroom = 2;
                    else if ( choice.equals("keluar") )
                        nextroom = 0;
                    else
                        System.out.println( "ERROR." );
                }
                if ( nextroom == 2 )
                {
                    System.out.println( "Kamu saat ini di ruang tamu sekarang mau kemana? \"kamar tidur\" / \"keluar\"" );
                    System.out.print( "> " );
                    choice = keyboard.nextLine();
                    if ( choice.equals("kamar tidur") )
                        nextroom = 3;
                    else if ( choice.equals("keluar") )
                        nextroom = 0;
                    else
                        System.out.println( "ERROR." );
                }
                if ( nextroom == 3 )
                {
                    System.out.println( "Kamu saat ini di kamar tidur sekarang mau kemana? \"kamar mandi\" / \"tidur\"" );
                    System.out.print( "> " );
                    choice = keyboard.nextLine();
                    if ( choice.equals("kamar mandi") )
                        nextroom = 4;
                    else if ( choice.equals("tidur") )
                        nextroom = 0;
                    else
                        System.out.println( "ERROR." );
                }
                if ( nextroom == 4 )
                {
                    System.out.println( "Kamu saat ini di kamar mandi sekarang mau kemana? \"ambil handuk\" / \"gajadi\"" );
                    System.out.print( "> " );
                    choice = keyboard.nextLine();
                    if ( choice.equals("ambil handuk") )
                        nextroom = 5;
                    else if ( choice.equals("gajadi") )
                        nextroom = 0;
                    else
                        System.out.println( "ERROR." );
                }
                if ( nextroom == 5 )
                {
                    System.out.println( "Setelah kamu ambil handuk sekarang mau kemana? \"mandi\" / \"balik kamar\"" );
                    System.out.print( "> " );
                    choice = keyboard.nextLine();
                    if ( choice.equals("mandi") )
                        nextroom = 6;
                    else if ( choice.equals("balik kamar") )
                        nextroom = 3;
                    else
                        System.out.println( "ERROR." );
                }
                if ( nextroom == 2 )
                {
                    System.out.println( "Kamu saat ini sedang mandi sekarang mau kemana? \"selesai\" / \"tamatina ae lah\"" );
                    System.out.print( "> " );
                    choice = keyboard.nextLine();
                    if ( choice.equals("selesai") )
                        nextroom = 0;
                    else if ( choice.equals("tamatin ae lah") )
                        nextroom = 0;
                    else
                        System.out.println( "ERROR." );
                }
            }

            System.out.println( "\nEND." );
        }
    }
    ```
  </Tab>
</Tabs>

## 63b. Baby Nim - [Link](https://programmingbydoing.com/a/baby-nim.html)

<Tabs>
  <Tab title="Task">
    Write a program that starts with three "piles" of 3 counters each. Let the player choose piles and remove counters until all the piles are empty.

    1. Start by placing counters (coins or toothpicks or something) into 3 piles.
    2. The player picks a pile, then removes one or more counters from that pile. (It's okay to take the whole pile.)
    3. The player picks a new pile, then removes one or more counters from that pile. (It's okay to pick the same pile as before.)
    4. Once all piles are empty, the game stops.

    You do not need to check for errors like a wrong pile name, or if someone tries to take more counters from the pile than the pile has.

    **Sample Output**

    Here is an example game, with starting piles of 3 counters.

    ```bash theme={null}
    A: 3	B: 3	C: 3

    Choose a pile: A
    How many to remove from pile A: 2

    A: 1	B: 3	C: 3

    Choose a pile: C
    How many to remove from pile C: 3

    A: 1	B: 3	C: 0

    Choose a pile: B
    How many to remove from pile B: 1

    A: 1	B: 2	C: 0

    Choose a pile: A
    How many to remove from pile A: 1

    A: 0	B: 2	C: 0

    Choose a pile: B
    How many to remove from pile B: 1

    A: 0	B: 1	C: 0

    Choose a pile: C
    How many to remove from pile C: 2

    A: 0	B: 1	C: -2

    Choose a pile: B
    How many to remove from pile B: 1

    A: 0	B: 0	C: -2

    All piles are empty. Good job!
    ```
  </Tab>

  <Tab title="Answer">
    ```java BabyNim.java theme={null}
    import java.util.Scanner;

    public class BabyNim
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            int pileA = 3, pileB = 3, pileC = 3;
            String pile;
            int num;

            System.out.printf("A: %s\tB: %s\tC: %s\n", pileA, pileB, pileC);

            while ( pileA > 0 || pileB > 0 || pileC > 0 )
            {
                System.out.print("\nChoose a pile: ");
                pile = keyboard.next();
                System.out.print("How many to remove from pile " + pile + ": ");
                num = keyboard.nextInt();

                if ( pile.equals("A") )
                    pileA -= num;
                else if ( pile.equals("B") )
                    pileB -= num;
                else if ( pile.equals("C") )
                    pileC -= num;

                System.out.printf("\nA: %s\tB: %s\tC: %s\n", pileA, pileB, pileC);
            }

            System.out.println("\nAll piles are empty. Good job!");
        }
    }
    ```
  </Tab>
</Tabs>

## 63c. Nim - [Link](https://programmingbydoing.com/a/nim.html)

<Tabs>
  <Tab title="Task">
    Nim is a strategy game between two players.

    1. Start by placing counters (coins or toothpicks or something) into 3 piles.
    2. Player #1 picks a pile, then removes one or more counters from that pile. (It's okay to take the whole pile.)
    3. Player #2 picks a pile, then removes one or more counters from that pile.
    4. Player #1 plays again. (It's okay to choose a different pile this time.)
    5. Whichever player is forced to take the last counter is the **LOSER**.

    Write a program that allows two human players to play Nim against each other. The program should detect when the last counter has been taken and declare a winner.

    At first, don't worry about detecting cheating. That is one of the bonus options.

    **Sample Output**

    Here is an example game, with starting piles of 3, 4, and 5 counters.

    ```bash theme={null}
    Player 1, enter your name: Alice
    Player 2, enter your name: Bob

    A: 3	B: 4	C: 5

    Alice, choose a pile: A
    How many to remove from pile A: 2

    A: 1	B: 4	C: 5

    Bob, choose a pile: C
    How many to remove from pile C: 3

    A: 1	B: 4	C: 2

    Alice, choose a pile: B
    How many to remove from pile B: 1

    A: 1	B: 3	C: 2

    Bob, choose a pile: B
    How many to remove from pile B: 1

    A: 1	B: 2	C: 2

    Alice, choose a pile: A
    How many to remove from pile A: 1

    A: 0	B: 2	C: 2

    Bob, choose a pile: B
    How many to remove from pile B: 1

    A: 0	B: 1	C: 2

    Alice, choose a pile: C
    How many to remove from pile C: 2

    A: 0	B: 1	C: 0

    Bob, choose a pile: B
    How many to remove from pile B: 1

    A: 0	B: 0	C: 0

    Alice, there are no counters left, so you WIN!
    ```
  </Tab>

  <Tab title="Answer">
    ```java Nim.java theme={null}
    import java.util.Scanner;

    public class Nim
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner(System.in);
            int pileA = 3, pileB = 4, pileC = 5;
            String pile;
            int num;

            System.out.print("Player 1, enter your name: ");
            String player1 = keyboard.next();
            System.out.print("Player 2, enter your name: ");
            String player2 = keyboard.next();

            System.out.printf("\nA: %s\tB: %s\tC: %s\n", pileA, pileB, pileC);

            while ( pileA > 0 || pileB > 0 || pileC > 0 )
            {
                System.out.print("\n" + player1 + ", choose a pile: ");
                pile = keyboard.next();
                System.out.print("How many to remove from pile " + pile + ": ");
                num = keyboard.nextInt();

                if ( pile.equals("A") )
                    pileA -= num;
                else if ( pile.equals("B") )
                    pileB -= num;
                else if ( pile.equals("C") )
                    pileC -= num;

                System.out.printf("\nA: %s\tB: %s\tC: %s\n", pileA, pileB, pileC);

                if ( pileA == 0 && pileB == 0 && pileC == 0 )
                {
                    System.out.println("\n" + player1 + ", there are no counters left, so you WIN!");
                    break;
                }

                System.out.print("\n" + player2 + ", choose a pile: ");
                pile = keyboard.next();
                System.out.print("How many to remove from pile " + pile + ": ");
                num = keyboard.nextInt();

                if ( pile.equals("A") )
                    pileA -= num;
                else if ( pile.equals("B") )
                    pileB -= num;
                else if ( pile.equals("C") )
                    pileC -= num;

                System.out.printf("\nA: %s\tB: %s\tC: %s\n", pileA, pileB, pileC);

                if ( pileA == 0 && pileB == 0 && pileC == 0 )
                {
                    System.out.println("\n" + player2 + ", there are no counters left, so you WIN!");
                    break;
                }
            }
        }
    }
    ```
  </Tab>
</Tabs>
