Fortran: Loops

There three main types of loops in Fortran.

  • do loop
  • do while loop
  • nested loop

There three also three types of control statements that can be used with Fortrain loops.

  • exit
  • cycle
  • stop

Example: do loop in Fortran


	program count

	do n = 1, 5
	   print*,  n
	end do
	   
	end program count
	

Output:

  1
  2
  3
  4
  5


Example: do loop in Fortran


	program factorial  
	implicit none  

	   ! define variables
	   integer :: fact = 1   
	   integer :: n  
	   
	   ! calculate factorials   
	   do n = 1, 5      
		  fact = fact * n 
		  ! print values
		  print*,  n, " ", fact   
	   end do 
	   
	end program factorial
	

Output:

  1      1
  2      2
  3      6
  4      24
  5      120

The implicit none statement forces the program to declare all variables, which is considered good style. Fortran has integer, character, real, complex, and logical data types.