
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Nested Loops with Examples
Loops in Java are called control statements because they decide the flow of execution of a program based on some condition. Java allows the nesting of loops, when we put a loop within another loop then we call it a nested loop. Nested loops are very useful when we need to iterate through a matrix array and when we need to do any pattern-based questions.
In this article, we are going to learn about Java nested loops with examples.
We can create nested loops for the following control statements ?
Let's discuss these nested loops with some examples
Nested for Loop
The for loop is the most used control statement in any programming language because it is easy to understand and implement. Loop iterate till the given condition is true. A nested for loop refers to for loop in another for loop.
Syntax
for (initial expression; conditional expression; increment/decrement expression){ // code to be executed for (initial expression; conditional expression; increment/decrement expression) { // code to be executed } }
initial expression ? executed once when loop begins.
conditional expression ? code will be executed till conditional expression is true.
increment/decrement expression ? to increment/decrement loop variable.
Example
The following program will perform the addition of two matrices using nested for loop.
public class Main{ public static void main(String args[]){ int mtr1[][] = {{2,7}, {9,2}}; int mtr2[][] = {{6,3}, {5,1}}; int add[][] = new int[2][2]; // Nested for loop for (int i= 0 ; i < 2 ; i++ ){ for (int j= 0 ; j < 2 ;j++ ){ add[i][j] = mtr1[i][j] + mtr2[i][j]; // Performing addition } } System.out.println("Sum of given two matrices ="); // Nested for loop to print the resulted matrix for (int i= 0 ; i < 2 ; i++ ){ for (int j= 0 ; j < 2 ;j++ ){ System.out.print(add[i][j]+"\t"); } System.out.println(); } } }
Output
Sum of given two matrices = 8 10 14 3
In the above code, we have taken two matrices mtr1 and mtr2 of size 2 rows and 2 columns. The first two for loops will run 4 times and during each iteration values of mtr1 and mtr2 will get stored in the third matrix add. The last two for loops will print the result on the screen.
Nested while Loop
The while loop is an entry control loop where condition is checked before moving to loop's body. The nested while loop refers to while loop inside another while loop.
Syntax
while (conditional expression) { // code will be executed till the conditional expression is true while (conditional expression) { // code will be executed till the conditional expression is true increment/decrement expression; // to increment/decrement loop variable } increment/decrement expression; // to increment/decrement loop variable }
Example
The following program will perform addition of two matrices using while loop.
public class Main{ public static void main(String args[]){ int mtr1[][] = {{2,7},{9,2}}; int mtr2[][] = {{6,3},{5,1}}; int add[][] = new int[2][2]; int i=0; // Nested while loop to perform addition while(i<2){ int j=0; while(j<2){ add[i][j] = mtr1[i][j] + mtr2[i][j]; j++; } i++; } System.out.println("Sum of given two matrices ="); i=0; // Nested while loop to print result while(i<2){ int j=0; while(j<2){ System.out.print(add[i][j]+"\t"); j++; } System.out.println(); i++; } } }
Output
Sum of given two matrices = 8 10 14 3
In the above code, we have followed the same logic as we did in the example 1 program but here we have used nested while loop instead of for loop. Again, we have taken two matrices mtr1 and mtr2 of size 2 rows and 2 columns. The first two while loops will run 4 times and during each iteration values of mtr1 and mtr2 will get stored in the third matrix add. The last two while loops will print the result on the screen.
Nested do while Loop
The do while loop is an exit control loop, where the loop's body gets executed before checking the given test condition. The nested do while loop can also be created by using a do-while loop inside another do-while loop.
Syntax
do{ //statement for the outer loop do{ //statement for the inner loop inner }while(condition B); }while(condition A)
Example
This Java program uses nested do-while loops to print a grid of asterisks (*).
public class Main { public static void main(String[] args) { int rows = 3; int cols = 4; int i = 1; do { int j = 1; do { System.out.print("* "); j++; } while (j <= cols); System.out.println(); i++; } while (i <= rows); } }
Output
* * * * * * * * * * * *
In the above code, the outer loop runs three times, once for each row, and initializes an inner loop for each row iteration. The inner loop runs four times, once for each column, and prints an asterisk followed by a space. After printing the required number of asterisks for a row, the inner loop ends, and the program moves to the next line. This process repeats until all rows are printed. The outer loop ensures that the inner loop runs for the specified number of rows, producing a 3x4 grid of asterisks.
Nested for each Loop
A for each loop is a special repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. The nested for each loop refers to use for each loop inside another for each loop.
Syntax
for (Type[] arrayElement : outerArray) { for (Type element : arrayElement) { // Inner loop statements } }
Example
This Java program demonstrates the use of nested for-each loops to iterate through a 2D array of strings and print its elements
public class NestedForEachExample3 { public static void main(String[] args) { String[][] array = { {"apple", "banana", "cherry"}, {"dog", "elephant", "frog"}, {"grape", "honey", "ice"} }; for (String[] row : array) { for (String element : row) { System.out.print(element + " "); } System.out.println(); } } }
The array variable is a 2D array with three rows, each containing three strings. The outer for-each loop iterates through each row of the array. For each row, the inner for-each loop iterates through the elements of that row. Each string element is printed followed by a space. After processing all elements in a row, the results in each row of the 2D array are printed on a new line.
Conclusion
A loop within another loop is called a nested loop. We have understood the nested for loops, and nested while loop with examples. These loops are used when we have to perform operations on 2-D arrays and matrices. We use them in pattern-based problems also.