# Loop

## DO Loop​

Calculate factorial:

src/07_factorial.f90
! Program : Find factorialPROGRAM factorial  IMPLICIT NONE  INTEGER :: input, ii, output = 1  PRINT *, "Input = "  READ *, input  DO ii = 1, input    output = output * ii  ENDDO  PRINT *, input, "! = ", outputEND PROGRAM factorial

We can have a step size in a DO loop with a third parameter:

DO i = 1, 100, 10  ! do somethingEND DO

Exit a loop based on condition:

DO i = 1, 10  CALL random_number(x)  IF (x > 0.5) EXITEND DO

Skip rest of current iteration with cycle:

DO i = 1, 10  IF (iseven(i)) CYCLE  ! do something with the odd numbersEND DO

Implied DO loops:

PRINT *, (i, i = 1, 10)

You can iterate multiple expressions:

PRINT *, (i, i**2, i = 0, 10)

With nested loops:

PRINT *, ((i*j, i = 1, 10), j = 1, 10)

DO concurrent: if the iterations of a DO loop are independent, we can use the CONCURRENT keyword to indicate, the loop can be iterated in parallel:

DO CONCURRENT (i = 1, 10)  ! do somethingEND DO

## DO WHILE​

src/07_print_even_numbers.f90
PROGRAM even_numbers  IMPLICIT NONE  INTEGER :: num  num = 1  DO WHILE (num <= 10)    IF (MODULO(num, 2) == 0) THEN      PRINT *, num    END IF    num = num + 1  END DOEND PROGRAM even_numbers