GroTechMinds

Nested For Loops and Enhanced For Loops in Java

Nested For Loops and Enhanced For Loops in Java

Introduction:

Loops are fundamental constructs in any programming language that allow us to execute a block of code as many times as desired. The for loop is particularly versatile because of its easy readability and reliability and is widely used among the various types of loops. Let us dive into two specific types of for loops in Java: nested for loops and enhanced for loops. 

Also Read :  A Comprehensive Guide on the Basic For Loop in Java

Nested For Loop:

     A nested for loop is a variation of the for loop, where we have a for loop inside another for loop. We call the loops outer loop and inner loop depending on their position. This loop structure is very useful and comes in handy in areas such as iterative calculations involving matrices, tables, or any scenario involving combinations of elements.

Syntax:

The Syntax of the for loop is given as follows

				
					for (initialization;
condition; increment/decrement)
{
‘Outer loop body’
        	for (initialization; condition; increment/decrement)
{
‘Inner loop body’
}
}

				
			
Initialization:

This is used to declare and initialize the loop control variable or variables. The loop control variable can also be declared globally and initialized inside the loop control statement.

Condition:

Before each iteration of the loop, this condition is checked. If the condition is true, the loop continues. If it is false, the loop terminates.

Increment/Decrement:

After each iteration of the loop, this determines whether incrementing or decrementing should happen to the value of the loop variable (i.e.,) updating of the variable’s value.

Outer Loop Body:

The outer loop body is the executable code that is controlled by the outer loop’s control statement. When control exits the outermost loop, the loop body stops iterating.

Inner Loop Body:

The Inner loop body is the executable code that is controlled by the inner loop’s control statement. When control exits the inner loop, the control goes to the outer loop’s control statement.

Examples of Nested For Loop:

Problem Statement 1: Print a 10 by 10 multiplication table for the first 10 natural numbers.

Solution: To print the multiplication table of the first 10 natural numbers, we need a nested for loop. In the outer loop, we iterate the natural numbers 1 through 10. On every iteration, we have an inner loop where the outer loop’s natural number is multiplied with natural numbers 1 through 10. We multiply 1 with natural numbers from 1 to 10 in 1st iteration of the outer loop and 10 with natural numbers 1 to 10 in the 10th iteration of the outer loop.

Using the ‘print(String s)’ method of the ‘PrintStream’ class, we print the inner loop iterations, separating every iteration’s result with two tabs “\t\t” spacing between them in the output console. Using the ‘println(String s)’ method of the ‘PrintStream’ class, we print the Outer loop iteration’s executable statement after the control has left the inner loop to the outer loop. So, in every iteration, we go to the next line with the outer loop’s executable statement.

Code Snippet:
				
					public static void main(String[] args)
{
int Size_of_the_Table = 10;    	
        	for (int i = 1; i <= Size_of_the_Table; i++)
        	{
                    	for (int j = 1; j <= Size_of_the_Table; j++)
                    	{
    	System.out.print(+i+"x"+j+"="+(i * j)+ "\t\t");
    	}
	System.out.println();
}
}

				
			
Output Screenshot:
java 1

Problem Statement 2: Write a program to seat 19 guests with 5 tables and a maximum of 4 guests per table.

Solution: To seat 19 guests with 5 tables and a maximum of 4 guests per table, we can use nested for loop. Here, the outer loop decides the table number and it iterates five times. On every outer loop iteration, the inner loop gets executed and iterates four times assigning the index positions of the String array ‘guests’.

Four index positions of the guest array are assigned per table per iteration of the outer loop. Using the ‘println(String s)’ method of the ‘PrintStream’ class, we print the seating arrangement in the output console.

Code Snippet:
				
					public static void main(String[] args)
{
int number_of_tables = 5;
int seats_per_table = 4;
String[] guests = {"Guest 1", "Guest 2", "Guest 3", "Guest 4", "Guest 5",
                    	"Guest 6", "Guest 7","Guest 8","Guest 9", "Guest 10",
                    	"Guest 11", "Guest 12", "Guest 13", "Guest 14", "Guest 15",
                    	"Guest 16","Guest 17", "Guest 18", "Guest 19"};
int guest_number = 0;
        	for (int table = 1; table <= number_of_tables; table++)
        	{
	System.out.println("Table " + table + ":");
	    	for (int seat = 1; seat <= seats_per_table; seat++)
    	{
      	if (guest_number < guests.length)
      	{
      	System.out.println("  Seat " + seat + ": " + guests[guest_number]);
      	guest_number++;
      	}
      	else
      	{
      	System.out.println("  Seat " + seat + ": [Empty]");
      	}
    	}
	System.out.println();
	}
}

				
			
Output Screenshot:
java 2
Enhanced For Loop:

The enhanced for loop also called the for-each loop, is designed for iterating arrays and collections. It enhances code readability, because of the simpler syntax and that makes it easier to work with arrays or collections without managing the loop control structure.

Syntax:

The Syntax of the for loop is given as follows.

				
					for (Variable declaration: array/collections)
{
‘Loop body’
}

				
			
Variable declaration:

We declare the data type of the variable (or object) in the array or collection that will hold each element of that array/collection during every iteration.

Arrays/Collections:

The array or collection to iterate over using the declared variable.

Loop Body:

The loop body is the executable code that is controlled by the loop’s control statement.

Examples of Enhanced For Loop:

Problem Statement 1: Write a program to calculate the total distance travelled by the driver in a week using for each loop. The distance travelled on every day of the week is given as follows.

DAYS DISTANCE COVERED (in kms)
Sunday 5.5
Monday 10.25
Tuesday 7
Wednesday 12.7
Thursday 5.1
Friday 1.2
Saturday 8.5

Solution: To calculate the total distance travelled by the driver in a week using for each loop, we create an array of double data type and store the distance travelled every day in an index position of that array respectively. Using for each loop, we get the value of every index position of that array and add it to another variable of float data type (we use float data type to round off and limit the decimal places).

Using ‘println(String s)’ method of the ‘PrintStream’ class, we print the variable where the sum of all the values present in the index positions are stored. In for each loop, for every iteration, one index position of the array is assigned to the variable declared in the control statement, and the value keeps on updating in every iteration.

Code Snippet:
				
					public static void main(String[] args)
{       	 	   
double[] distance_travelled_per_day = {5.5, 10.25, 7.0, 12.7, 5.1, 1.2, 8.5};
float total_distance = 0;
        	for (double distance : distance_travelled_per_day)
        	{
                    	total_distance =(float) (distance+total_distance);
        	}
System.out.println("Total distance traveled in the week: " + total_distance + " km");
}

				
			
Output Screenshot:
java 4

Problem Statement 2: Write a program to calculate the average bill amount received in a restaurant for every weekday from the daily bill amount received.

Solution: To calculate the average bill amount received in a restaurant from the daily bill amount received we use a nested for each loop. We create an array of double data type for every day of the weekday and store the bill amounts received in the index positions of the respective array. We create another array of string data type to store the name of the weekday. Using an enhanced for loop as the outer loop, we iterate the String array and store the values in the index positions in a String variable on every iteration respectively.

Using switch case, we assign the values of the array that contains bill amounts to a newly created array of double data type. We create an inner for loop for this newly created array and calculate the average of all the values in the index positions of this array.

On every outer loop iteration, the entire array which contains the bill amounts for a weekday is assigned to a newly created array. In the inner loop, this newly created array’s values in its index positions are added to calculate the average. In this way, we can calculate the average value of the bill amounts on every weekday separately.

On every outer loop iteration, using ‘println(String s)’ method of the ‘PrintStream’ class, we print the value of the variable where the average of all the bill amount values of the respective weekday are present to the console.

Code Snippet:
				
					public static void main(String[] args) {
String[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
double[] billAmountsMonday = {1000, 500, 300, 1200, 100, 400, 1000, 900};
double[] billAmountsTuesday = {400, 600, 700, 1000, 900, 30, 500, 300, 1000};
double[] billAmountsWednesday = {290, 750, 300, 1200, 100, 500, 600, 1350, 1000, 900};
double[] billAmountsThursday = {580, 500, 300, 1200, 100, 400, 630, 700, 1000, 1100, 500};
double[] billAmountsFriday = {890, 500, 300, 1200, 100, 400, 633, 700, 1000, 900, 1000};
        	for (String weekday : weekdays)
        	{
        	double[] currentBillAmounts;
                    	switch (weekday)
                    	{
        		    	case "Monday":
        	  	  currentBillAmounts = billAmountsMonday;
        	    	break;
        	    	case "Tuesday":
        	    	currentBillAmounts = billAmountsTuesday;
        	    	break;
        	    	case "Wednesday":
        	    	currentBillAmounts = billAmountsWednesday;
        	    	break;
        	    	case "Thursday":
        	    	currentBillAmounts = billAmountsThursday;
        	    	break;
        	    	case "Friday":
        	    	currentBillAmounts = billAmountsFriday;
        	    	break;
        		}
        	double sum = 0;
                    	for (double amount : currentBillAmounts)
                    	{
        	 	sum=sum+amount;
        		}
        	float avgBill = (float) (sum / currentBillAmounts.length);
        	System.out.println("The average Bill amount on " + weekday + " is " + avgBill);
        	}
}

				
			
Output Screenshot:
java 5

Problem Statement 3: Write a program to create a String from the values in the index positions of an ‘ArrayList’.

Solution: To create a String from the values in the index positions of an ‘ArrayList’, we use the ‘add(String e)’ method of the ‘ArrayList’ class which implements the ‘List’ Interface to add the values to its index positions. Using for each loop, we cycle (iterate) the values of the index position of the ‘ArrayList’ and add the String values to the new string created.

On every iteration, the values present in each index position are added to the newly created String and we can print it using the ‘print(String s)’ method of the ‘PrintStream’ class.

Code Snippet:
				
					package core_java;
import java.util.ArrayList;
public class Enhanced_For_Loop_arraylist {
public static void main(String[] args)
{
ArrayList<String> GTM = new ArrayList<>();
GTM.add("Software");
GTM.add("Testing");
GTM.add("by");
GTM.add("MKT");
String final_str="";
        	for (String str : GTM)
        	{
        	final_str=final_str+" "+str;
	}
System.out.println("The String created is : "+final_str);
}       	
}

				
			
Output Screenshot:
java 6
Conclusion:

Nested loops are widely used where we involve multiple levels of iteration, such as seating arrangements, timetable scheduling, etc., The enhanced for loop is a powerful feature in Java that simplifies the process of iterating over arrays and collections. Simplicity, reduced risk of errors, and easy readability are some of its several advantages. By understanding and utilising the enhanced for loop and nested for loop, we can write more efficient, and more maintainable code.

Upskill Yourself
Consult Us