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

# For Loops

> 14 assignments

## 64. Counting with a For Loop - [Link](https://programmingbydoing.com/a/counting-for.html)

<Tabs>
  <Tab title="Task">
    As you saw in [Counting with a While Loop](https://programmingbydoing.com/a/counting-while.html), a `while` loop can be used to to make something happen an exact number of times.

    However, this isn't our best choice. `while` loops are designed to keep going *as long* as something is true. But if we know in advance how many times we want to do something, Java has a special kind of loop designed just for making a variable change values: the `for` loop.

    `for` loops are best when 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.

    On the other hand, `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.

    **Sample Output**

    ```bash theme={null}
    Type in a message, and I'll display it five times.
    Message: Hey, hey.
    1. Hey, hey.
    2. Hey, hey.
    3. Hey, hey.
    4. Hey, hey.
    5. Hey, hey.
    ```
  </Tab>

  <Tab title="Answer">
    Type in the following code, and get it to compile. Then answer the questions down below.

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

    public class CountingFor
    {
        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();

            for ( int n = 1 ; n <= 5 ; n = n+1 )
            {
                System.out.println( n + ". " + message );
            }
        }
    }
    ```
  </Tab>

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

    1. What does n = n+1 do? Remove it and see what happens. (Then put it back.)
       > Answer: It increments the value of `n` by 1.
    2. What does int n = 1 do? Remove it and see what happens. (Then put it back.)
       > Answer: It initializes the value of `n` to 1.
    3. Change the code so that the loop repeats ten times instead of five.
       > Answer: Change `n <= 5` to `n <= 10`.
    4. See if you can change the for loop so that the message starts at 2 and counts by twos, like so:
       ```bash theme={null}
       Type in a message, and I'll display it ten times.
       Message: qwerty
       2. qwerty
       4. qwerty
       6. qwerty
       8. qwerty
       10. qwerty
       ```
       > Answer: Change `int n = 1` to `int n = 2` and `n = n+1` to `n = n+2`.
  </Tab>
</Tabs>

## 65. Ten Times - [Link](https://programmingbydoing.com/a/ten-times.html)

<Tabs>
  <Tab title="Task">
    Write a program that prints the important phrase "Mr. Mitchell is cool." on the screen ten times. Use a `for` loop to do it.

    **Sample Output**

    <CodeGroup>
      ```bash Sample 1 theme={null}
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      Mr. Mitchell is cool.
      ```

      ```bash Sample 2 theme={null}
      If you want, you can number the lines of output like so:

      1. Mr. Mitchell is cool.
      2. Mr. Mitchell is cool.
      3. Mr. Mitchell is cool.
      4. Mr. Mitchell is cool.
      5. Mr. Mitchell is cool.
      6. Mr. Mitchell is cool.
      7. Mr. Mitchell is cool.
      8. Mr. Mitchell is cool.
      9. Mr. Mitchell is cool.
      10. Mr. Mitchell is cool.
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Answer">
    ```java TenTimes.java theme={null}
    public class TenTimes
    {
        public static void main( String[] args )
        {
            for ( int n = 1 ; n <= 10 ; n++ )
            {
                System.out.printf( "%d. Mr. Mitchell is cool.\n", n );
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 66. Counting Machine - [Link](https://programmingbydoing.com/a/counting-machine.html)

<Tabs>
  <Tab title="Task">
    Write a program that gets an integer from the user. Count from 0 to that number. Use a `for` loop to do it.

    **Sample Output**

    <CodeGroup>
      ```bash Sample 1 theme={null}
      Count to: 19
      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
      ```

      ```bash Sample 2 theme={null}
      Count to: 8
      0 1 2 3 4 5 6 7 8
      ```

      ```bash Sample 3 theme={null}
      Count to: 25
      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
      ```
    </CodeGroup>
  </Tab>

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

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

            System.out.print( "Count to: " );
            int number = keyboard.nextInt();

            for ( int n = 0 ; n <= number ; n++ )
            {
                System.out.printf( "%d ", n );
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 67. Counting Machine Revisited - [Link](https://programmingbydoing.com/a/counting-machine-revisited.html)

<Tabs>
  <Tab title="Task">
    Write a program that gets three integers from the user. Count from the first number to the second number in increments of the third number. Use a `for` loop to do it.

    **Sample Output**

    <CodeGroup>
      ```bash Sample 1 theme={null}
      Count from: 4
      Count to  : 13
      Count by  : 3

      4 7 10 13
      ```

      ```bash Sample 2 theme={null}
      Count from: 5
      Count to  : 20
      Count by  : 5

      5 10 15 20
      ```

      ```bash Sample 3 theme={null}
      Count from: 2
      Count to  : 10
      Count by  : 1

      2 3 4 5 6 7 8 9 10
      ```
    </CodeGroup>
  </Tab>

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

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

            System.out.print( "Count from: " );
            int from = keyboard.nextInt();
            System.out.print( "Count to: " );
            int to = keyboard.nextInt();
            System.out.print( "Count by: " );
            int by = keyboard.nextInt();

            for ( int n = from ; n <= to ; n = n+by )
            {
                System.out.printf( "%d ", n );
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 68. Counting By Halves - [Link](https://programmingbydoing.com/a/counting-by-halves.html)

<Tabs>
  <Tab title="Task">
    Write a program that uses a `for` loop. With the loop, make the variable `x` go from -10 to 10, counting by 0.5. (This means that `x` can't be an `int`.)

    **Sample Output**

    ```bash theme={null}
    x
    ------
    -10.0
    -9.5
    -9.0
    -8.5
    -8.0
    ...
    9.0
    9.5
    10.0
    ```
  </Tab>

  <Tab title="Answer">
    ```java CountingByHalves.java theme={null}
    public class CountingByHalves
    {
        public static void main( String[] args )
        {
            System.out.println( "x" );
            System.out.println( "------" );

            for ( double x = -10.0 ; x <= 10.0 ; x = x+0.5 )
            {
                System.out.println( x );
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 69. Xs and Ys - [Link](https://programmingbydoing.com/a/xs-and-ys.html)

<Tabs>
  <Tab title="Task">
    Write another program that uses a `for` loop. With the loop, make the variable `x` go from -10 to 10, counting by 0.5. (This means that `x` can't be an `int`.)

    Inside the body of the loop, make another variable `y` become the current value of `x` squared. Then display the current values of both `x` and `y`.

    To get your output to line up like mine, use a tab.

    **Sample Output**

    ```bash theme={null}
    x      y
    -----------------
    -10.0   100.00
    -9.5    90.25
    -9.0    81.00
    -8.5
    -8.0    64.00
    ...
    9.0     81.00
    9.5     90.25
    10.0    100.00
    ```
  </Tab>

  <Tab title="Answer">
    ```java XsAndYs.java theme={null}
    public class XsAndYs
    {
        public static void main( String[] args )
        {
            System.out.println( "x\ty" );
            System.out.println( "-----------------" );

            for ( double x = -10.0 ; x <= 10.0 ; x += 0.5 )
            {
                double y = Math.pow(x, 2);
                System.out.printf( "%s\t%s\n", x, y );
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 70. Noticing Even Numbers - [Link](https://programmingbydoing.com/a/noticing-even-numbers.html)

<Tabs>
  <Tab title="Task">
    Write a program that uses a `for` loop to display all the numbers from 1 to 20, marking those which are even (divisible by two). It should use modulus by 2: if the remainder is zero, it's divisible by 2.

    This means you'll need an `if` statement inside the loop.

    ```java theme={null}
    for ( <stuff> )
    {
        if ( <something with modulus> )
        {
            System.out.println( <something> );
        }
        else
        {
            System.out.println( <something different> );
        }
    }
    ```

    **Sample Output**

    ```bash theme={null}
    1
    2 <
    3
    4 <
    5
    6 <
    7
    8 <
    9
    10 <
    11
    12 <
    13
    14 <
    15
    16 <
    17
    18 <
    19
    20 <
    ```
  </Tab>

  <Tab title="Answer">
    ```java NoticingEvenNumbers.java theme={null}
    public class NoticingEvenNumbers
    {
        public static void main( String[] args )
        {
            for ( int n = 1 ; n <= 20 ; n++ )
            {
                if ( n % 2 == 0 )
                {
                    System.out.println( n + " <" );
                }
                else
                {
                    System.out.println( n );
                }
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 71. Fizz Buzz - [Link](https://programmingbydoing.com/a/fizzbuzz.html)

<Tabs>
  <Tab title="Task">
    Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

    The output of your program will look something like this:

    ```bash theme={null}
    1
    2
    Fizz
    4
    Buzz
    Fizz
    7
    8
    Fizz
    Buzz
    11
    Fizz
    13
    14
    FizzBuzz
    16
    17
    Fizz
    19
    Buzz
    ...
    97
    98
    Fizz
    Buzz
    ```
  </Tab>

  <Tab title="Answer">
    ```java FizzBuzz.java theme={null}
    public class FizzBuzz
    {
        public static void main( String[] args )
        {
            for ( int n = 1 ; n <= 100 ; n++ )
            {
                if ( n % 3 == 0 && n % 5 == 0 )
                {
                    System.out.println( "FizzBuzz" );
                }
                else if ( n % 3 == 0 )
                {
                    System.out.println( "Fizz" );
                }
                else if ( n % 5 == 0 )
                {
                    System.out.println( "Buzz" );
                }
                else
                {
                    System.out.println( n );
                }
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 72. Letter at a Time - [Link](https://programmingbydoing.com/a/letter-at-a-time.html)

<Tabs>
  <Tab title="Task">
    Did you know that using a loop, you can examine a String one letter at a time? The two key built-in String methods are `length()` and `charAt()`.

    * `length()` returns an `int` representing the total number of characters in the String (including punctuation and whitespace). For example, if the variable str contains the String `"hello"`, then `str.length()` will return `5`.
    * `charAt( int n )` returns the `n`th character (`char`) in the String. The character positions are zero-based, so if the variable `str` contains the String `"ligature"`, then `str.charAt(0)` will return `'l'`, and `str.charAt(4)` will return `'t'`.

    **Files Needed**

    * [LetterAtATime.java](https://programmingbydoing.com/a/examples/LetterAtATime.java)

    **Sample Output**

    ```bash theme={null}
    What is your message? A man, a plan, a canal: Panama!

    Your message is 31 characters long.
    The first character is at position 0 and is 'A'.
    The last character is at position 30 and is '!'.

    Here are all the characters, one at a time:

        0 - 'A'
        1 - ' '
        2 - 'm'
        3 - 'a'
        4 - 'n'
        5 - ','
        6 - ' '
        7 - 'a'
        8 - ' '
        9 - 'p'
        10 - 'l'
        11 - 'a'
        12 - 'n'
        13 - ','
        14 - ' '
        15 - 'a'
        16 - ' '
        17 - 'c'
        18 - 'a'
        19 - 'n'
        20 - 'a'
        21 - 'l'
        22 - ':'
        23 - ' '
        24 - 'P'
        25 - 'a'
        26 - 'n'
        27 - 'a'
        28 - 'm'
        29 - 'a'
        30 - '!'

    Your message contains the letter 'a' 10 times. Isn't that interesting?
    ```
  </Tab>

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

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

            System.out.print("What is your message? ");
            String message = kb.nextLine();

            System.out.println("\nYour message is " + message.length() + " characters long.");
            System.out.println("The first character is at position 0 and is '" + message.charAt(0) + "'.");
            int lastpos = message.length() - 1;
            System.out.println("The last character is at position " + lastpos + " and is '" + message.charAt(lastpos) + "'.");
            System.out.println("\nHere are all the characters, one at a time:\n");

            for ( int i=0; i<message.length(); i++ )
            {
                System.out.println("\t" + i + " - '" + message.charAt(i) + "'");
            }

            int a_count = 0;

            for ( int i=0; i<message.length(); i++ )
            {
                char letter = message.charAt(i);
                if ( letter == 'a' || letter == 'A' )
                {
                    a_count++;
                }
            }

            System.out.println("\nYour message contains the letter 'a' " + a_count + " times. Isn't that interesting?");
        }
    }
    ```
  </Tab>

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

    1. The `for` loop is defined so that it repeats as long as `i < message.length()`. Try changing it to `<=`. What happens? Answer in a comment, then change it back.
       > Answer: It will throw an `IndexOutOfBoundsException` because the index is out of bounds.
    2. If a string variable contains the value `"box"`, what is its `length()`? What is the position of the last character (the `'x'`)?
       > Answer: The length is 3, and the position of the last character is 2.
    3. So, why does the `for` loop repeat as long as `i < message.length()` instead of `i <= message.length()`?
       > Answer: Because the index is zero-based, and the last index is `message.length() - 1`.
    4. Currently the code prints out the number of 'a's in the message. Change it so that it prints out the number of vowels (`a A e E i I o O u U`).
       > Answer: Change `if ( letter == 'a' || letter == 'A' )` to `if ( letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' )`.
  </Tab>
</Tabs>

## 73. For Loop Challenge - [Link](https://programmingbydoing.com/a/for-loop-challenge.html)

<Tabs>
  <Tab title="Task">
    Get a blank sheet of paper (scratch paper is fine) and something to write with. Tell Mr. Mitchell you'd like to take the **For Loop Challenge**. He will ask you to write an arbitrary `for` loop on the sheet of paper. If you do it without any mistakes, you will receive full points.

    You may take this challenge more than once, but you'll receive 5 fewer points each time you do it. The `for` loop you must write will be different each time.

    Here's an example of what you'll be asked to do:

    $~~~~~$"Write a for loop that makes the variable j go from 15 to 30, counting by 3s."
  </Tab>

  <Tab title="Answer">
    ```java ForLoopChallenge.java theme={null}
    public class ForLoopChallenge
    {
        public static void main( String[] args )
        {
            for ( int j = 15 ; j <= 30 ; j += 3 )
            {
                System.out.println( j );
            }
        }
    }
    ```
  </Tab>
</Tabs>

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

<Tabs>
  <Tab title="Task">
    Write a program that gets an integer from the user. Add up all the numbers from 1 to that number, and display the total. Use a `for` loop to do it.

    You have done something like this [before](https://programmingbydoing.com/a/adding-values-in-a-loop.html).

    **Sample Output**

    <CodeGroup>
      ```bash Sample 1 theme={null}
      Number: 5

      1 2 3 4 5
      The sum is 15.
      ```

      ```bash Sample 2 theme={null}
      Number: 8

      1 2 3 4 5 6 7 8
      The sum is 36.
      ```
    </CodeGroup>
  </Tab>

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

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

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

            int sum = 0;
            for ( int n = 1 ; n <= number ; n++ )
            {
                System.out.print( n + " " );
                sum += n;
            }

            System.out.printf( "\nThe sum is %s.\n", sum );
        }
    }
    ```
  </Tab>
</Tabs>

## 116. A Refresher - [Link](https://programmingbydoing.com/a/a-refresher.html)

<Tabs>
  <Tab title="Task">
    Just a short program to refresh your memory about how to program. Write a program that prompts the user for a name. Then display that name ten times. You must use a loop. If the name given is "Mitchell", display it only five times.

    **Sample Output**

    <CodeGroup>
      ```bash Sample 1 theme={null}
      What is your name: gump

      gump
      gump
      gump
      gump
      gump
      gump
      gump
      gump
      gump
      gump
      ```

      ```bash Sample 2 theme={null}
      What is your name: Mitchell

      Mitchell
      Mitchell
      Mitchell
      Mitchell
      Mitchell
      ```
    </CodeGroup>
  </Tab>

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

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

            System.out.print( "What is your name: " );
            String name = keyboard.nextLine();

            if ( name.equals("Mitchell") ) {
                for ( int n = 1 ; n <= 5 ; n++ )
                {
                    System.out.println( name );
                }
            } else {
                for ( int n = 1 ; n <= 10 ; n++ )
                {
                    System.out.println( name );
                }
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 117. Refresher Challenge - [Link](https://programmingbydoing.com/a/refresher2.html)

<Tabs>
  <Tab title="Task">
    This assignment is almost the same as A [Refresher](https://programmingbydoing.com/a/a-refresher.html).

    Write a program that prompts the user for a name. Then display that name ten times using a loop. However, if the name given is "Mitchell", display it only five times.

    So here's the challenge: write the program using only one `if` statement (no `else`) and *one* `for` loop.

    **Sample Output**

    <CodeGroup>
      ```bash Sample 1 theme={null}
      What is your name: gump

      gump
      gump
      gump
      gump
      gump
      gump
      gump
      gump
      gump
      gump
      ```

      ```bash Sample 2 theme={null}
      What is your name: Mitchell

      Mitchell
      Mitchell
      Mitchell
      Mitchell
      Mitchell
      ```
    </CodeGroup>
  </Tab>

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

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

            System.out.print( "What is your name: " );
            String name = keyboard.nextLine();
            System.out.println();

            for ( int n = 1 ; n <= 10 ; n++ )
            {
                if ( name.equals("Mitchell") && n > 5 ) {
                    break;
                }
                System.out.println( name );
            }
        }
    }
    ```
  </Tab>
</Tabs>

## 118. Displaying Some Multiples - [Link](https://programmingbydoing.com/a/displaying-some-multiples.html)

<Tabs>
  <Tab title="Task">
    Write a program to calculate the multiples of a given number. Have the user enter a number, and then use a `for` loop to display all the multiples of that number from 1 to 12. It is not necessary to use a function.

    You *must* use a `for` loop.

    **Sample Output**

    ```bash theme={null}
    Choose a number: 7

    7x1 = 7
    7x2 = 14
    7x3 = 21
    7x4 = 28
    7x5 = 35
    7x6 = 42
    7x7 = 49
    7x8 = 56
    7x9 = 63
    7x10 = 70
    7x11 = 77
    7x12 = 84
    ```
  </Tab>

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

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

            System.out.print( "Choose a number: " );
            int number = keyboard.nextInt();
            System.out.println();

            for ( int n = 1 ; n <= 12 ; n++ )
            {
                System.out.printf( "%s x %s = %s\n", number, n, number * n );
            }
        }
    }
    ```
  </Tab>
</Tabs>
