Recursion and Loops

JavaJavaBeginner
Practice Now

Introduction

Computers are often used to automate repetitive tasks. Repeating tasks without making errors is something that computers do well and people do poorly. Like conditional expressions, loops can also be nested one in another, but this will make our program hard to read and the performance will not be good. Try to avoid nested loops. There are three types of loops in Java. We'll learn them one by one in this lab.

Content

Recursion in computer science is a technique where the solution to a problem depends on the solutions to smaller instances of the same problem (as opposed to iteration). The approach is called recursion and can be applied to many types of problems. Recursion is one of the central ideas of computer science. The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite number of statements. In the same manner, an infinite number of computations can be described by a finite recursive program, even if this program contains no explicit repetitions.

Example:

Write the following code in the /home/labex/project/recursionTest.java file:

public class recursionTest{
    public static int fibonacci(int n){
        if(n<=2){
            return 1;
        }else{
            return fibonacci(n-1)+fibonacci(n-2);
        }
    }
    public static void main(String[] args){
        int res = recursionTest.fibonacci(10);
        System.out.println(res);
    }
}

Output:

Run the recursionTest.java file using the following commands:

javac /home/labex/project/recursionTest.java
java recursionTest

See the output:

55

While Loop

When entering a while loop, first the condition will be checked. The while loop will always run until the condition is false. The syntax is like this:

Example:

Write the following code in the /home/labex/project/whileTest.java file:

public class whileTest
{
    public static void main(String[] args)
    {
        int x = 1;
        // exit when x is bigger than 3, the inner code will run 3 times in all.
        while (x <= 3)
        {
            System.out.println("x = " + x);
            // increment the value of x by 1 each time for next iteration
            x++;
        }
    }
}

Output:

Run the whileTest.java file using the following commands:

javac /home/labex/project/whileTest.java
java whileTest

See the output:

x = 1
x = 2
x = 3

Do-While Loop

This loop is very similar to the while loop, but there is one difference. Whatever the value of condition be, the loop will always run at least once; thereafter the condition is checked. So, sometimes maybe it's not fit for some circumstances. The syntax is:

Example:

Write the following code in the /home/labex/project/doWhileTest.java file:

public class doWhileTest
{
    public static void main(String[] args)
    {
        int x = 1;
        do
        {
            // the code below will run first, then condition is checked.
            System.out.println("x = " + x);
            x++;
        }
        while (x <= 3);
    }
}

Output:

Run the doWhileTest.java file using the following commands:

javac /home/labex/project/doWhileTest.java
java doWhileTest

See the output:

x = 1
x = 2
x = 3

For Loop

The for loop looks like this:

Example:

for (init expression; condition expression; increment expression)
{
    // statements here
}

The init condition marking the start of a for loop will run only once. Conditional expression will be checked each time before entering the loop. It is used for testing the exit condition for a loop and must return a boolean value. Once the condition is true, the statements in the loop are executed; thereafter the increment expression will be executed to modify the values of counter or other variables for next iteration.

Example:

Write the following code in the /home/labex/project/forTest.java file:

public class forTest
{
    public static void main(String[] args)
    {
        // for loop begins when x=1 till x<=3
        for (int x = 1; x <= 3; x++) {
            System.out.println("x = " + x);
        }
    }
}

Output:

Run the forTest.java file using the following commands:

javac /home/labex/project/forTest.java
java forTest

See the output:

x = 1
x = 2
x = 3

You can exit the loop whenever you want in the loop body by using code like continue or break in an if block of statements. break will exit the whole loop while continue will only quit the current iteration and perform the next iteration (if the condition is true).

Example:

Write the following code in the /home/labex/project/loopTest.java file:

public class loopTest
{
    public static void main(String[] args)
    {
        // for loop begins when x=1 till x<=3
        for (int x = 1; x <= 3; x++) {
            if(x==2){
                // exit the whole loop
                break;
                // continue will only quit the current iteration, and do next iteration
                // you can delete the break expression and use continue. See the output.
                // continue;
            }
            System.out.println("x = " + x);
        }
    }
}

Output:

Run the loopTest.java file using the following commands:

javac /home/labex/project/loopTest.java
java loopTest

See the output:

x = 1

Summary

In this lab, we learned three types of loops. For loop and while loop are easy to learn whereas do-while loop is not very perfect logically. You should choose it very carefully.

Other Java Tutorials you may like