A nested for loop is just a for loop inside a for loop.
The output is:
As you can see the outer loop index (variable i) goes from 0 to 2 (three times), and the inner loop index (variable j) goes from 0 to 1 (two times). Thus we get 6 lines.
This example demonstrates how to use nested for loops to iterate over a two-dimensional array.
Here is an example that uses nested for loops to sort an array of integers:
This code implements the bubble sort algorithm, which employs nested for loops to compare and swap elements in the array until it is sorted in ascending order.
At each step in the outer iteration (index “i”) we compare every element with every element to its right and if they are in the wrong order, it swaps them. To understand this algorithm, we should print the array at each step of the outer array:
The output will be:
The first line is simply the given array. In the second line, note that the algorithm has compared 2 and 4 (and left them intact). It compared 4 and 8 (and left them intact). Then it compared 8 and 1 (and moved the 8 to the right) and in this manner moved 8 till it reached a number larger than 8 (i.e. 9).So 8 stopped there but when 9 was compared with 3, 9 began moving to the right. The end result of these maneuvers is that by the end of the second line, the largest number (i.e. 9) is at the rightmost location, i.e., where it needs to be. Similarly, by the end of the third line, the second largest number (i.e., 8) is where it needs to be), and so on. By the time all the sweeps are done we are guaranteed that every number is in its correct place.
Here is another example of using nested for loops to multiply two matrices.
In the above code, we initialize the result matrix as an empty array and then perform matrix multiplication using nested for loops. The outermost loop iterates over the rows of the first matrix, the second loop iterates over the columns of the second matrix, and the innermost loop calculates the dot product of the corresponding row of the first matrix and the column of the second matrix, which is then stored in the result matrix. Because the input matrices are of size 2x3 and 3x2, the final product is of size 2x2, as shown above.
If you liked learning about nested for loops, checkout our blogpost on bubblesort!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.