A loop is used to implement computations of the repetitive type. With the loop construct, we can control the start and end of repeated executions using boolean conditions. In Java there are three types of loops that can be used: while loops, do-while loops and for loops.
The while loop
Exercise: Decimal to String
Given a decimal number, convert it to a String to print on the display. Example input: 1234 Example output: “1234”
Solution
In this exercise, we can manipulate the data type conversion technique we studied in the previous section, where we used the ASCII encoding scheme to calculate the integer values of characters representing the number symbols. In order to do the conversion operation iteratively, over each digit in the number, we can use a while loop, which divides takes the modulo 10 of the number to extract the smallest digit at each step in the iteration, and continues to shift the number value to obtain the next decimal digit.
Exercise: Guessing Game
Let’s implement a game using Java according to the following instructions. A program randomly picks a number
- The user inputs a guess, and if the guess is correct, the program outputs the message “Correct guess”
- On the other hand, if number is larger, the program outputs “Your guess is too low”
- If the number is smaller, the program outputs “Your guess is too large”
- The game continues until the guess is correct
Solution
In order to create the indefinite continuation of the game, we can simply use a while loop with the inner condition set to ‘true’. The condition of termination of the game will be when the number is correctly guessed, where the loop can simply be exited using the ‘break’ keyword. Please check out the code below for an example implementation.
The do-while loop
The for loop
Exercise: Multiplication Table
Write a Java program that prints all the entries in the Multiplication Table for the multiplication of numbers between 1 and 9.
Solution
In this exercise, we need to implement the computation of combinations of two numbers, both ranging between the values of 1 and 9. Here, we can use this opportunity to use the nested loop concept, to iterate through the values of one variable at a time. For simplicity, we use the for loop that increments the value of each integer variable one at a time, until both reaches the value of 9. Here is a simple implementation of the program.