Fortran – Nested Loops

Fortran Nested Loops

In this guide, we will discuss Fortran Nested Loops. You can use one or more loop construct inside any another loop construct. You can also put labels on loops.

Syntax

iloop: do i = 1, 3
   print*, "i: ", i
   
   jloop: do j = 1, 3         
      print*, "j: ", j         
      
      kloop: do k = 1, 3
         print*, "k: ", k
         
      end do kloop
   end do jloop  
end do iloop

Example

program nestedLoop 
implicit none

   integer:: i, j, k
   
   iloop: do i = 1, 3      
      jloop: do j = 1, 3         
         kloop: do k = 1, 3              
         
            print*, "(i, j, k): ", i, j, k               
            
         end do kloop       
      end do jloop
   end do iloop

end program nestedLoop  

When the above code is compiled and executed, it produces the following result −

 (i, j, k):            1           1           1
 (i, j, k):            1           1           2
 (i, j, k):            1           1           3
 (i, j, k):            1           2           1
 (i, j, k):            1           2           2
 (i, j, k):            1           2           3
 (i, j, k):            1           3           1
 (i, j, k):            1           3           2
 (i, j, k):            1           3           3
 (i, j, k):            2           1           1
 (i, j, k):            2           1           2
 (i, j, k):            2           1           3
 (i, j, k):            2           2           1
 (i, j, k):            2           2           2
 (i, j, k):            2           2           3
 (i, j, k):            2           3           1
 (i, j, k):            2           3           2
 (i, j, k):            2           3           3
 (i, j, k):            3           1           1
 (i, j, k):            3           1           2
 (i, j, k):            3           1           3
 (i, j, k):            3           2           1
 (i, j, k):            3           2           2
 (i, j, k):            3           2           3
 (i, j, k):            3           3           1
 (i, j, k):            3           3           2
 (i, j, k):            3           3           3

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply