Get up to 80 % extra points for free! More info:

Lesson 6 - Loops in Java

In the previous exercise, Solved tasks for Java lesson 5, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on for and while loops in Java instead of a thorough-full lesson? Here it is:

Using a for loop to execute code 3 times:

for (int i = 0; i < 3; i++) { // runs 3 times in total
    System.out.println("Knock");
}
System.out.println("Penny!");

Accessing the loop control variable each iteration:

for (int i = 1; i <= 10; i++) {
    System.out.printf("%d ", i); // prints the current value of the loop control variable
}

Nesting loops to work with tabular data:

System.out.println("Here's a simple multiplication table using nested loops:");
for (int j = 1; j <= 10; j++) {
    for (int i = 1; i <= 10; i++) {
        System.out.printf("%d ", i * j);
    }
    System.out.println();
}

Using a while loop when we don't know how many times the code is going to repeat:

Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to our calculator");
String goOn = "yes";
while (goOn.equals("yes"))
{
    System.out.println("Enter the first number:");
    double a = Double.parseDouble(scanner.nextLine());
    System.out.println("Enter the second number:");
    double b = Double.parseDouble(scanner.nextLine());
    System.out.println("Choose one of the following operations:");
    System.out.println("1 - addition");
    System.out.println("2 - subtraction");
    System.out.println("3 - multiplication");
    System.out.println("4 - division");
    int option = Integer.parseInt(scanner.nextLine());
    double result = 0;
    switch (option)
    {
        case 1:
            result = a + b;
        break;
        case 2:
            result = a - b;
        break;
        case 3:
            result = a * b;
        break;
        case 4:
            result = a / b;
        break;
    }
    if ((option > 0) && (option < 5))
    {
        System.out.println("Result: " + result);
    }
    else
    {
        System.out.println("Invalid option");
    }
    System.out.println("Would you like to make another calculation? [yes/no]");
    goOn = scanner.nextLine();
}
System.out.println("Thank you for using our calculator.");

Notice using equals() to compare Strings.

Would you like to learn more? A complete lesson on this topic follows.

In the previous tutorial, Solved tasks for Java lesson 5, we learned about conditions in Java. In today's lesson, we're going to introduce you all to loops. After today's lesson, we'll have almost covered all of the basic constructs to be able to create reasonable applications.

Loops

The word loop suggests that something is going to repeat. When we want a program to do something 100 times, certainly we'll not write the same code 100x. Instead, we'll put it in a loop. There are several types of loops. We'll explain how to use them, and of course, make practical examples.

The for loop

This loop has a determined fixed number of steps and contains a control variable, typically an integer, which changes values gradually during the loop. The for loop syntax is the following:

for (variable; condition; command)
  • variable is the control variable which is set to an initial value (usually 0, because in programming, everything starts from zero, never from one). For example: int i = 0. Of course, we could also create the variable somewhere above it, and we wouldn't have to write the int keyword, but usually we declare int i there.
  • condition is the condition for executing the next step of the loop. Once it becomes false, the whole loop is terminated. The condition may be for example i < 10.
  • command tells us what will happen to our variable on every step i.e. whether it should be increased or decreased. We use special ++ and -- operators for this. Of course, you can use these operators outside the loop as well, they decrease or increase a variable by 1.

Let's create a simple example, most of us certainly know Sheldon from The Big Bang Theory. For those who don't, we'll simulate a situation where a guy knocks on his neighbor's door. He always knocks 3 times and then yells: "Penny!". Our code, without a loop, would look like this:

System.out.println("Knock");
System.out.println("Knock");
System.out.println("Knock");
System.out.println("Penny!");

However, using loops, we no longer have to copy the same code over and over:

for (int i=0; i < 3; i++)
{
    System.out.println("Knock");
}
System.out.println("Penny!");

Console application
Knock
Knock
Knock
Penny!

The loop will run through 3 times. At the very beginning, i is set to zero, the loop then prints "Knock" and increases i by one. It continues in the same way with values one and two. Once i hits three, the condition i < 3 is no longer true and the loop terminates. Loops have the same rules for omitting curly brackets as conditions. In this case, they may be omitted since the loop contains only one command. Now, we can simply change value 3 to 10 in the loop declaration. The command will execute 10x without writing anything extra. Surely you can see that loops are a very powerful tool.

Now let's put the variable incrementation to use. We'll print the numbers from one to ten. Since we don't want our output to be on separate lines, we'll use the print() method rather than println().

for (int i = 1; i <= 10; i++)
{
    System.out.print(i + " ");
}

We can see that the control variable has a different value after each iteration (iteration is one step of the loop). Notice that this time, the loop doesn't start from zero because we want the initial value to be 1 and the last one to be 10. Just keep in mind that in programming, almost everything starts from zero, we'll find out why later.

Now let's print a simple multiplication table that contains multiples of numbers from 1 to 10. All we need to do is to declare a loop from 1 to 10 and multiply the control variable with the current multiplier. It might look like this:

System.out.println("Here's a simple multiplication table using loops:");
for (int i = 1; i <= 10; i++)
{
    System.out.print(i + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 2) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 3) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 4) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 5) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 6) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 7) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 8) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 9) + " ");
}
System.out.println();
for (int i = 1; i <= 10; i++)
{
    System.out.print((i * 10) + " ");
}

The result:

Console application
Simple multiplication table using loops:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

The program works nicely, but we still wrote a lot. Honestly, we could break it down even more since all it does is repeat 10 times while increasing the multiplier. What we'll do is nest the loops (put one inside the other):

System.out.println("Here's a simple multiplication table using nested loops:");
for (int j = 1; j <= 10; j++)
{
    for (int i = 1; i <= 10; i++)
    {
        System.out.print((i * j) + " ");
    }
    System.out.println();
}

Makes a big difference, doesn't it? Obviously, we can't use i in both loops since they are nested and would count as a re-declaration. The variable j of the outer loop gains the values from 1 to 10. During each iteration of the loop, another inner loop with the variable i is executed. We already know that it'll write the multiples, in this case, it multiplies by the variable j. After each time the inner loop terminates it's necessary to break the line, it's done by System.out.println().

Let's make one more program where we'll practice working with an outer variable. The application will be able to calculate an arbitrary power of an arbitrary number:

Scanner scanner = new Scanner(System.in);
System.out.println("Exponent calculator");
System.out.println("===================");
System.out.println("Enter the base: ");
int a = Integer.parseInt(scanner.nextLine());
System.out.println("Enter the exponent: ");
int n = Integer.parseInt(scanner.nextLine());

int result = a;
for (int i = 0; i < (n - 1); i++)
{
    result = result * a;
}

System.out.println("Result: " + result);
System.out.println("Thank you for using our exponent calculator");

I'm sure we all know how powers (exponents) work. But just to be sure, let me remind that, e.g. 2^3 = 2 * 2 * 2. So, we compute a^n by multiplying the number a by the number a for n-1 times. Of course, the result must be stored in a variable. Initially, it'll have a value of a and this value will be gradually multiplying during the loop. We can see that our result variable in the loop body is normally accessible. If, however, we create a variable in a loop body, this variable will be no longer accessible after the loop terminates.

Console application
Exponent calculator
==========================
Enter the base:
2
Enter the exponent:
3
Result: 8
Thank you for using our exponent calculator

Now, we know what some practical uses of the for loop are. Remember that it has a fixed amount of iterations. We shouldn't modify the control variable from inside the loop since the program could get stuck in an infinite loop. Here's the last example of what you should not do:

// this code is wrong
for (int i = 1; i <= 10; i++)
{
    i = 1;
}

Ouch, we can see that the program is stuck. The loop always increments the variable i, but it is always set back to 1. Meaning that it never reaches values > 10 and the loop never ends. Close the program window or use the Stop button next to the console window.

The while loop

The while loop works differently, it simply repeats the commands in a block while a condition is true. The syntax of the loop is the following:

while (condition)
{
    // commands
}

If you realized that the for loop can be simulated using the while loop, you are right :) The for loop is actually a special case of the while loop. However, the while loop is used for slightly different things. Typically, we call some method returning a logical true/false value, in the while loop parentheses. We could rewrite the original for-loop example to use the while loop instead:

int i = 1;
while (i <= 10)
{
    System.out.print(i + " ");
    i++;
}

But this is not an ideal example of using the while loop. Let's take our calculator from previous lessons and improve it a little bit. We'll add an ability to enter more math problems. The program will not end immediately, but it'll ask the user whether they wish to calculate another math problem. Let's remind the original version of the code (this is the version with switch, but feel free to use the if-else version, it depends on you):

Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to our calculator");
System.out.println("Enter the first number:");
double a = Double.parseDouble(scanner.nextLine());
System.out.println("Enter the second number:");
double b = Double.parseDouble(scanner.nextLine());
System.out.println("Choose one of the following operations:");
System.out.println("1 - addition");
System.out.println("2 - subtraction");
System.out.println("3 - multiplication");
System.out.println("4 - division");
int option = Integer.parseInt(scanner.nextLine());
double result = 0;
switch (option)
{
    case 1:
        result = a + b;
    break;
    case 2:
        result = a - b;
    break;
    case 3:
        result = a * b;
    break;
    case 4:
        result = a / b;
    break;
}
if ((option > 0) && (option < 5))
{
    System.out.println("Result: " + result);
}
else
{
    System.out.println("Invalid option");
}
System.out.println("Thank you for using our calculator.");

Now, we'll put almost all the code into a while loop. Our condition will be that the user entered "yes", so we'll check the content of a goOn variable. This variable will be set to "yes" at the beginning since the program has to begin somehow, then we'll assign the user's input to it:

Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to our calculator");
String goOn = "yes";
while (goOn.equals("yes"))
{
    System.out.println("Enter the first number:");
    double a = Double.parseDouble(scanner.nextLine());
    System.out.println("Enter the second number:");
    double b = Double.parseDouble(scanner.nextLine());
    System.out.println("Choose one of the following operations:");
    System.out.println("1 - addition");
    System.out.println("2 - subtraction");
    System.out.println("3 - multiplication");
    System.out.println("4 - division");
    int option = Integer.parseInt(scanner.nextLine());
    double result = 0;
    switch (option)
    {
        case 1:
            result = a + b;
        break;
        case 2:
            result = a - b;
        break;
        case 3:
            result = a * b;
        break;
        case 4:
            result = a / b;
        break;
    }
    if ((option > 0) && (option < 5))
    {
        System.out.println("Result: " + result);
    }
    else
    {
        System.out.println("Invalid option");
    }
    System.out.println("Would you like to make another calculation? [yes/no]");
    goOn = scanner.nextLine();
}
System.out.println("Thank you for using our calculator.");

Notice that we ask whether strings are equal using the equals() method, not using the == operator! It's because String is a reference data type. The condition ("Text" == "Text") is wrong, we have to write ("Text".equals("Text")). We'll discover why is that in the object-oriented course.

Console application
Welcome to our calculator
Enter the first number:
12
Enter the second number:
128
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
1
Result: 140
Would you like to make another calculation? [yes/no]
yes
Enter the first number
-10.5
Enter the second number:

Our application can now be used multiple times and is almost complete. Note: this is one of the few codes that cannot be run online since our user bot would have to repeat inputs. In the next lesson, Solved tasks for Java lesson 6, we'll show you how to work with arrays.

You've already learned quite a lot! Nothing better than a little noggin exercise, right? :)

In the following exercise, Solved tasks for Java lesson 6, we're gonna practice our knowledge from previous lessons.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 50x (64.47 kB)
Application includes source codes in language Java

 

Previous article
Solved tasks for Java lesson 5
All articles in this section
Java Basic Constructs
Skip article
(not recommended)
Solved tasks for Java lesson 6
Article has been written for you by David Capka Hartinger
Avatar
User rating:
3 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities