Skip to main content

Beginner Java Exercise: While Loops

Java has a 3 types of loops. The one we're going to be focusing on is a while loop. A while loop allows you to repeat a certain portion of the code a number of times.

The while loop is tested with the loop-continuation-conditional.

while (x < 10) { }

In the example above, the less than operator (<) is the loop-continuation-conditional. It states that while x is less than 10, statements within the loop body { } will continue to execute.

The above example will continue infinitely because there are no statements within the loop body to ever trigger the loop-continuation-conditional to be false.

A more realistic example would be

int x = 0;

while (x < 10) {
        System.out.print(x + " - ");
        x++;
}

Zero is assigned to the x variable.
A while loop is generated testing whether x is less than 0.
If so, the user will see x printed on their screen.
x is incremented by 1 and the while loop repeats.

During the first iteration, x is 0.
Is 0 < 10?
Yes, so display x: display 0.
Increment x by 1. So 0 + 1 = 1.
- Side note, x++ is the same as x = x +1.
x is assigned the value of 1.
The while loop repeats testing whether 1 < 10.
Yes, so display x: display 1.
...
Until finally x is incremented to 10.
Is 10 < 10?
No. 10 is equal to 10 but it's not less than 10.
The script terminates.
Your result should look like this:

0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 -

You may be asking yourself why the result is displayed on the same line. System.out.print() is identical to System.out.println() with the exception that System.out.println() also inserts a new line after the statement is executed.

You may also be asking yourself why isn't x + " - " performing the sum of x and " - ". When a string is involved, the + operator is treated as a concatenation operator appending one string to another, or a number to a string. So 1 + 2 would yield 3, while 1 + "2" would yield 12.

Another thing you may do is test whether the number being displayed is the last number in the sequence. If so, no trailing dash needs to be displayed.

To do this,

int x = 0;
string dash;

while (x < 10) {
        dash = (9 == x) ? "" : " - ";

        System.out.print(x + comma);
        x++;
}

The above code runs exactly the same as the previously mentioned one except it removes the last dash. Your result will look like this:

0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9

It initiates the variable dash and sets it to the string data type.

It performs the test within the loop body to see if the last number is reached. In this case we know that the maximum amount of iterations that the loop can have is 10; the loop will terminate once it reaches 10. So when x reaches 1 less than the maximum number, in this case 9, we want the dash variable to be assigned an empty string, otherwise assign a dash.

You may be wondering what the code dash = (9 == x) ? "" : " - ";  is.

It's a short way of writing an if (condition) { statement } else { other statement }

The ?: is called a ternary operator in Java. It basically substitutes the if and else.

The above code can be re-written as

if (9 == x) {
        dash = "";
} else {
        dash = " - ";
}

In the following example, we'll generate 2 random numbers and ask the person what the answer to the sum of the 2 numbers is.

While the answer is wrong, it'll keep asking the person to try again. Once the user guesses the answer correctly, the while loop will terminate and the next statement will execute which just notifies the user that they guessed the answer correctly.


Comments

Popular posts from this blog

Beginner Java Exercise: Sentinel Values and Do-While Loops

In my previous post on while loops, we used a loop-continuation-condition to test the arguments. In this example, we'll loop at a sentinel-controlled loop. The sentinel value is a special input value that tests the condition within the while loop. To jump right to it, we'll test if an int variable is not equal to 0. The data != 0 within the while (data != 0) { ... } is the sentinel-controlled-condition. In the following example, we'll keep adding an integer to itself until the user enters 0. Once the user enters 0, the loop will break and the user will be displayed with the sum of all of the integers that he/she has entered. As you can see from the code above, the code is somewhat redundant. It asks the user to enter an integer twice: Once before the loop begins, and an x amount of times within the loop (until the user enters 0). A better approach would be through a do-while loop. In a do-while loop, you "do" something "while" the condition

Programming Language Concepts Questions/Answers Part 3

1. What is an associative array? - An unordered collection of data elements that are indexed by keys. 2. Each element of an associative array is a pair consisting of a _______ and a _______. - key and a value 3. True or False? Java supports associative arrays? - True. As a matter of fact, Perl, Python, Ruby, C++, C# and F# do too. 4. What are associative arrays called in Perl? - hashes 5. Why are associative arrays in Perl called hashes? - Because their elements are stored and retrieved with a hash function 6. What character does a hash in Perl begin with? % 7. In Perl, each key is a _____ and each value is a _______. - string - scalar 8. In Perl, subscripting is done using _______ and _______. - braces and keys 9. In Perl, how are elements removed from hashes? - using delete 10. In Perl, the ________ operator tests whether a particular value is a key in a hash. - exists 11. What are associative arrays called in Python? - dictionaries 12. What is a dif

Creating your own ArrayList in Java

Wanted to show that certain data structures in Java can be created by you. In this example, we'll go ahead and create an ArrayList data structure that has some of the methods that the built in ArrayList class has. We'll create 2 constructors: The default constructor that creates an ArrayList with a default size of 10. Constructor that allows an initial size to be passed to the array. We'll also create a number of methods: void add(Object x);  A method that allows you to place an Object at the end of the ArrayList. void add(int index, Object x);  A method that allows you to place a value at a given location. Object get(int index):  Allows you to retrieve a value of the arrayList array from a given location. int size();  Allows you to get the number of elements currently in the Arraylist. boolean isEmpty();  Tests to see if the Arraylist is empty. boolean isIn(Object x);  A method that sees if a particular object exist in the arrayList. int find(Object x);