Loops in Java are used to repeat similar steps multiple times until the condition of the loop becomes wrong. When a loop exists inside the body of another loop, it is called the nested loop. The nesting of the loop creates the concept of outer and inner loops. The inner loop runs until its condition gets the wrong value for each outer loop iteration.

Outline 

  • How Nested Loop Works
  • Time Complexity
  • Independent and Dependent Nested Loop

How Nested Loop Works

The nested loops generally improve the readability and manageability of the code as they generally represent multidimensional data. The outer loop runs its first iteration and the inner loop runs all its iterations and then it goes back to the outer loop to run its iterations again. This process keeps on repeating until the outer loop gets the false value. The following picture describes the working structure of the nested loop with the help of a flow chart:

Syntax in Java

for(OuterInitialValue; OuterCondition; increment/decrement) //Outer loop{
    for(InnerInitialValue; InnerCondition; increment/decrement) //Inner loop    {        //Body or statements of the inner loop
    }    //Body or statements of the outer loop
}
  • The above syntax uses the for keyword with the small braces() containing all the values of the arguments.
  • The initial value is the starting point for the loop, the condition is the endpoint, and increment/decrement is the steps taken to reach the condition.
  • Firstly, the Outer loop will execute with the OuterInitialValue and then start the iterations of the inner loop until the InnerCondition becomes false.
  • At that moment, the control will be transferred to the outer loop with the incremented or decremented value.

Example 1: Working of Nested for Loop in Java

The first example describes the working of the nested for loops that simply explains how many iterations are done by each loop:

public class NestedLoop {
    public static void main(String[] args) {        //Outer loop with 2 iterations
        for (int m = 1; m <= 2; m++) {
            System.out.println("");
            System.out.println("Outer Loop: "+"\'"+m+"\'");            //Inner loop with 3 iterations
            for (int n = 1; n <= 3; n++) {
                System.out.println("Inner Loop: "+n);
            }
        }
    }
}
  • Create a for loop within the main method’s body that only takes two iterations to print the Outer Loop message using the variable m.
  • Create another for loop inside the body of the outer for loop with the variable n to run three iterations with the message Inner Loop.
  • The outer loop runs its first iteration and the inner loop completes all its iteration.
  • Then, for the second outer loop iteration, the inner loop runs three times again.

Output

Example 2: Nested Loop to Return Tables in Java

The following example displays the mathematical times’ tables using the nested for loop:

public class NestedLoop {
    public static void main(String[] args) {        //Outer loop to print the rows for all the tables
        for (int a = 1; a <=10; a++){            //Inner loop to print the columns for all the tables
            for (int z = 2; z < 10; z++){
                System.out.print((a*z)+"\t");
            }
            System.out.println();
        }
    }
}
  • The outer loop with the variable a starts the loop from value 1 till the value gets to 10 with an increment of 1 value per iteration.
  • The inner loop with variable z starts from 2 to print the 2*Times table in the first column until the value becomes 9 as the condition says less than 10.
  • It simply multiplies the inner loop values with 1 from the outer loop to print the first row from 2 to 9.
  • After that, the outer loop increases its value by 1 and reruns the inner loop to print the next row.
  • This process goes on until the outer loop gets the value 11.
  • The outer loop body also contains the print() method to break the line after the completion of each iteration.

Output

Example 3: Nested Loop to Design Star Pattern in Java

This example creates a certain pattern called the inverted left-half pyramid with random characters like stars. This is very helpful in building the logical sense of exploring the code by making changes to the nested loop:

public class NestedLoop {
    public static void main(String[] args) {
        int stars = 5;        //Outer loop to manage the number of rows/lines in the pattern
        for (int e = 1; e <= stars; e++){            //First inner loop to print the spaces in each row
            for (int f = 1; f < e; f++){
                System.out.print(" ");
            }            //Second inner loop to print the stars in each row
            for (int g=stars; g>=e; g--){
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
  • Initialize the variable named stars in the main method to store the value for the height and width of the pyramid.
  • Design the outer loop with the variable e starting from 1 till the value is stored in the stars variable.
  • Create the first inner loop to print the spaces required in each row as the spaces start coming in the second row in increasing order.
  • The second inner loop is responsible for printing the stars in a decreasing pattern starting from 5 starts until 1.

Output

Example 4: Getting a List of Subjects Opted by Students Using Nested Loop

This example uses the nested loop in Java language to build a case scenario to understand the concept better. It will ask for the number of students with their names to store them in the arrays. Then, it simply stores the number of subjects for each student individually:

Scanner sc1 = new Scanner(System.in);
//Getting the number of students from the user
System.out.print("Enter the number of students: ");
int NumberofStudents = sc1.nextInt();
String[] students = new String[NumberofStudents];
//Getting the name of all the students from the user
for (int i = 0; i < NumberofStudents; i++) {
    System.out.print("Enter the name of student " + (i + 1) + ": ");
    students[i] = sc1.next();//storing the names of all the students in an array}
  • The Scanner class is used to get the input from the user and store them in the arrays.
  • Get the number of the student first and store the value in the NumberofStudents variable. 
  • Use the “NumberofStudents” variable in the for loop here to get the names of each of the students and store their values in the students variable.

The following code takes the input in the “NumberofSubjects” and using nested for loop allows the user to input subjects for each student:

//Getting the number of subjects for each student
System.out.print("Enter the number of subjects: ");
int NumberofSubjects = sc1.nextInt();
String[][] subjects = new String[NumberofStudents][NumberofSubjects];
//Getting the name of all the subjects for each of the students
for (int i = 0; i < NumberofStudents; i++) {
    for (int j = 0; j < NumberofSubjects; j++) {
        System.out.print("Enter subject " + (j + 1) + " for student " + students[i] + ": ");
          subjects[i][j] = sc1.next();//storing the subjects for all the student in an array
    }
}

Again use the nested for loop to display the subjects for each student with their names as well in the Student Information section:

// Displaying the information of all the students'
System.out.println("\nStudent Information:");
for (int i = 0; i < NumberofStudents; i++) {
    System.out.print(students[i] + ": ");
    for (int j = 0; j < NumberofSubjects; j++) {
        System.out.print(subjects[i][j] + " ");
    }
    System.out.println("");
}

Complete Code

import java.util.Scanner;
public class NestedLoop {
    public static void main(String[] args) {
        Scanner sc1 = new Scanner(System.in);
        //Getting the number of students from the user
        System.out.print("Enter the number of students: ");
        int NumberofStudents = sc1.nextInt();
        String[] students = new String[NumberofStudents];
        //Getting the name of all the students from the user
        for (int i = 0; i < NumberofStudents; i++) {
            System.out.print("Enter the name of student " + (i + 1) + ": ");
            students[i] = sc1.next();//storing the names of all the students in an array
        }
        //Getting the number of subjects for each student
        System.out.print("Enter the number of subjects: ");
        int NumberofSubjects = sc1.nextInt();
        String[][] subjects = new String[NumberofStudents][NumberofSubjects];
        //Getting the name of all the subjects for each of the students
        for (int i = 0; i < NumberofStudents; i++) {
            for (int j = 0; j < NumberofSubjects; j++) {
                System.out.print("Enter subject " + (j + 1) + " for student " + students[i] + ": ");
                subjects[i][j] = sc1.next();//storing the subjects for all the student in an array
            }
        }
        // Displaying the information of all the students'
        System.out.println("\nStudent Information:");
        for (int i = 0; i < NumberofStudents; i++) {
            System.out.print(students[i] + ": ");
            for (int j = 0; j < NumberofSubjects; j++) {
                System.out.print(subjects[i][j] + " ");
            }
            System.out.println("");
        }
    }
}

Output

Time Complexity 

The time complexity means how many iterations would the loop take to get the false value or exit the loop body. There are three complexity cases called best, average, and worst but normally the developer will always consider the worst value. The best value suggests the earliest loop termination, the average gets the middle value, and the worst case tells the most number of iterations any loop would take. Some of the basic types of time complexities are mentioned as follows:

  • Constant time O(1): means that the loop always runs for the same number of iterations
  • Linear time O(n): loop increases linearly with constant steps
  • Logarithmic time O(log n): occurs when the loop starts decreasing with each step
  • Quadratic time O(n2): the loop increases its steps non-linearly 

The time complexities for each of the loops used in this guide are explained in the following table:

Sr No.LoopTime Complexity
Example 1for (int m = 1; m <= 2; m++)O(1), constant
Example 1for (int n = 1; n <= 3; n++)O(1), constant
Example 2for (int a = 1; a <=10; a++)O(1), constant iterations
Example 2for (int z = 2; z < 10; z++)O(1), constant iterations 
Example 3for (int e = 1; e <= stars; e++)O(n), n is the value stored in the stars variable
Example 3for (int f = 1; f < e; f++)O(m), Dependent inner loop
Example 3for (int g = stars; g >= e; g–)O(m), m is the variable of the outer loop
Example 4for (int i = 0; i < NumberofStudents; i++)O(n), n is the number of iterations
Example 4for (int j = 0; j < NumberofSubjects; j++)O(n), n is the number of iterations

Independent and Dependent Nested Loop

This is a bit advanced level concept related to the nested loop which helps in understanding the workings of the loop individually as well. Let’s differentiate the

Independent Nested Loop

The independent loop means that all the loops in the nested loop structure don’t depend on each other. In this concept, the outer loop runs separately and the inner loop will complete its own iteration without considering the value of the outer loop or vice versa. The syntax with the structure of the independent loop is mentioned below:

for(int a=1; a<=5; a++) {
    for(int b=1; b<=10; b++) {
        //Both Loops are Independent
    }}

Dependent Nested Loop

The dependent loop means one of the nested loops depends on the other loop to get the argument values of the loop. The following code block contains the syntax of the dependent loop as the inner loop depends on the outer loop to get its condition value. The inner loop’s variable which is “b” depends on the “a” variable to run the iterations as it will not run at all in the first iteration. This is due to the dependency created at the condition of the inner loop:

for(int a=1; a<5; a++){
    for(int b=1; b<a; b++) {
        //Inner loop is Dependent on Outer Loop
    }
}

That’s all about it.

Conclusion

The nested for loop means that single or multiple loops are running inside another loop’s body to manage the multi-dimensional data. It is mainly used to work with the matrix and the data with multiple fields like tables in the database. The nesting of the loops is also used to design different 2D structures or patterns that effectively build logical sense. The dependent and independent loops in the nested loop are a bit difficult or an advanced concept.