Nested loop

If a loop exists inside the body of another loop, it’s called a nested loop. Here’s an example of the nested for loop.

Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as “loop inside loop“. Syntax for Nested For loop: for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop }

What is the use of nested loop?

Image result for java nested loop

The inner loop is nested inside the outer loop. Nested loops are useful when for each pass through the outer loop, you need to repeat some action on the data in the outer loop. For example, you read a file line by line and for each line you must count how many times the word “the” is found.

If a loop exists inside the body of another loop, it’s called a nested loop. Here’s an example of the nested for loop. // outer loop for (int i = 1; i <= 5; ++i) { // codes // inner loop for(int j = 1; j <=2; ++j) { // codes } .. } Here, we are using a for loop inside another for loop.

Example,

// outer loop
for (int i = 1; i <= 5; ++i) {
  // codes

  // inner loop
  for(int j = 1; j <=2; ++j) {
    // codes
  }
..
}

Here, we are using a for loop inside another for loop.

We can use the nested loop to iterate through each day of a week for 3 weeks.

In this case, we can create a loop to iterate three times (3 weeks). And, inside the loop, we can create another loop to iterate 7 times (7 days).


Example 1: Java Nested for Loop

class Main {
  public static void main(String[] args) {

    int weeks = 3;
    int days = 7;

    // outer loop prints weeks
    for (int i = 1; i <= weeks; ++i) {
      System.out.println("Week: " + i);

      // inner loop prints days
      for (int j = 1; j <= days; ++j) {
        System.out.println("  Day: " + j);
      }
    }
  }
}

Run Code

Output

Week: 1
  Day: 1
  Day: 2
  Day: 3
    .....  ..  ....
Week: 2
  Day: 1
  Day: 2
  Day: 3
  ....  ..  ....
....  .. ....

If they are the same size, loop through and make sure the character at each index matches. If at any point we find characters that don’t match, we know it is not equal. If we loop through the entire thing without finding a difference, then the two arrays are equal.

Leave a comment

Design a site like this with WordPress.com
Get started