Different Nested Loops possible in Java
If a loop is written inside the body of the another loop, it is referred as a nested loops. There are three different types of loops supported in Java. They are for loop, while loop and do while loop. This loops can be nested with similar type or with the combination of other loops. There is no limitations on number of times loops are nested. Moreover, we can nest them in any combination.
- Nested for loop
- Nested while loop
- Nested do-while loop
Nested for loop
We are using a for loop inside the other for loop. So, in all it will execute for n * m times where n is number of iteration of outer loop and m is number of iteration of inner loop.
The syntax of nested for loop is as shown below.
for (initialization; condition; increment / decrement) {
for (initialization; condition; increment / decrement) {
// statement of inside loop
}
// statement of outer loop
}
Example : In this example, we are using two for loops to draw a pattern of *.
// Program to print pattern of * using nested loops
class Main {
public static void main(String[] args) {
// Declaring variable
int i, j;
// Using nested for loop and printing
for (i = 1; i <= 5; i++) {
for (j = i; j <= 5; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Output
*****
****
***
**
*
Nested While loop
We are using a while loop inside the other while loop. So, in all it will execute for n * m times where n is number of iteration of outer loop and m is number of iteration of inner loop.
The syntax of nested while loop is as listed below.
while (condition) {
while (condition) {
// statement of inside loop
}
// statement of outer loop
}
Example : In this example, we are using two while loops to print a multiplication table of 5 and 6.
// Program to print multiplication table of 5 and 6 using nested loops
class Main {
public static void main(String[] args) {
// Declaring variable
int i = 5, j;
// Using nested for loop and printing
while (i <= 6) {
System.out.println("Multiplication table of " + i);
j = 1;
while (j <= 10) {
System.out.println(i + " * " + j + " = " + (i * j));
j++;
}
i++;
}
}
}
Output
Multiplication table of 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Multiplication table of 6
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
6 * 10 = 60
Nested do-while loop
We are using a do-while loop inside the other do-while loop. So, in all it will execute for n * m times where n is number of iteration of outer loop and m is number of iteration of inner loop.
The syntax of nested do-while loop is as shown below.
do {
do {
// statement of inside loop
} while (condition);
// statement of outer loop
} while (condition);
Example : In this example we are having a menu driven program that computes addition and multiplication of n numbers.
import java.util.Scanner;
// Menu driven program using nested loops
class Main {
public static void main(String[] args) {
int ch, count;
Scanner sc = new Scanner(System.in);
int a, result, n;
do {
System.out.println("Enter your choice \n1. Addition \n2. Multiplication");
ch = sc.nextInt();
switch (ch) {
case 1:
count = 0;
result = 0;
System.out.println("Enter how many numbers you want to add");
n = sc.nextInt();
do {
System.out.println("Enter a number " + (count + 1));
a = sc.nextInt();
result = result + a;
count++;
} while (count < n);
System.out.println("Summation result is " + result);
break;
case 2:
count = 0;
result = 1;
System.out.println("Enter how many numbers you want to multiply");
n = sc.nextInt();
do {
System.out.println("Enter a number " + (count + 1));
a = sc.nextInt();
result = result * a;
count++;
} while (count < n);
System.out.println("Multiplication result is " + result);
break;
}
} while (ch <= 4);
}
}
Output
Enter your choice
1. Addition
2. Multiplication
1
Enter how many numbers you want to add
3
Enter a number 1
10
Enter a number 2
20
Enter a number 3
30
Summation result is 60
Enter your choice
1. Addition
2. Multiplication
2
Enter how many numbers you want to multiply
3
Enter a number 1
10
Enter a number 2
20
Enter a number 3
30
Multiplication result is 6000
Enter your choice
1. Addition
2. Multiplication
3
Examples using Hybrid Nested Loops
Example 1 : Find repeated words in a string using for loop and while loop
In this example, we are finding the list of words repeated in the given String.
// Program to find repeated words in a string using nested loops
public class Main {
public static void main(String[] args) {
String s = "Life is like a book. Life is like a cup of tea. Life is like a rose garden. Life is like a dream";
int count;
// Converts the string into lowercase
s = s.toLowerCase();
// Splitting the string to words for comparison
String w[] = s.split(" ");
// Finding the repeated words from a string
System.out.println("Finding repeated words in a string : ");
int i = 0;
while (i < w.length) {
count = 1;
for (int j = i + 1; j < w.length; j++) {
if (w[i].equals(w[j])) {
count++;
// Setting w[j] to 0 again to avoid printing visited word
w[j] = "0";
}
}
// Displays the repeated word if count is greater than 1
if (count > 1 && w[i] != "0")
System.out.println(w[i]);
i++;
}
}
}
Output
Finding repeated words in a string :
life
is
like
a
Example 2 : Print transpose of a matrix
In this example, we are printing the transpose of a two dimensional matrix.
// Program to print transpose of a matrix using nested loops
public class Main {
public static void main(String[] args) {
int r, c;
// Initialize matrix a
int a[][] = {
{
1,
2,
3
},
{
4,
5,
6
},
{
7,
8,
9
}
};
// Finding the number of rows and columns present in given matrix
r = a.length;
c = a[0].length;
// Declare array to store transpose
int t[][] = new int[c][r];
int j;
// Calculates transpose of given matrix
for (int i = 0; i < c; i++) {
j = 0;
while (j < r) {
t[i][j] = a[j][i];
j++;
}
}
// Printing transpose
for (int i = 0; i < c; i++) {
for (j = 0; j < r; j++) {
System.out.print(t[i][j] + " ");
}
System.out.println();
}
}
}
Output
1 4 7
2 5 8
3 6 9
Example 3 : Print pattern using do-while and for loop
In this example, we are printing the transpose of a two dimensional matrix.
public class Main {
public static void main(String[] args) {
int i = 1, j, n = 5;
do {
// this loop is used to print the n
for (j = n; j >= 1; j--) {
// this loop is used to print numbers in a line
if (j != i)
System.out.print(j);
else
System.out.print("*");
}
System.out.println("");
i++;
} while (i < n);
}
}
Output
5432*
543*1
54*21
5*321
*4321
Summary
The knowledge of Nested loops in Java is very useful while working on a real time applications. There are various combinations that can be used depending on requirement. In this tutorial, we covered nested loops in Java along with the examples of hybrid nested loops. As per the requirement of an application, we can choose an appropriate loops. We learned in detail about this looping with an example. All in all, this tutorial, covers everything that you need to know in order to have a clear view on Nesting loops in Java.
References