Programming Fundamentals/Loops/Fortran
Appearance
loops.f90
[edit | edit source]! This program demonstrates While, Do, and For loop counting using
! user-designated start, stop, and increment values.
!
! References:
! https://www.tutorialspoint.com/fortran
! https://en.wikibooks.org/wiki/Fortran
! This program asks the user to select Fahrenheit or Celsius conversion
! and input a given temperature. Then the program converts the given
! temperature and displays the result.
! References:
! https://www.tutorialspoint.com/fortran
! https://en.wikibooks.org/wiki/Fortran
program loops
integer :: get_value
integer :: start, stop, increment
start = get_value("starting")
stop = get_value("ending")
increment = get_value("increment")
call while_loop(start, stop, increment)
call do_loop(start, stop, increment)
call for_loop(start, stop, increment)
end program
function get_value(label) result (value)
character(*) :: label
integer :: value
print ("(a a a)"), "Enter ", label, " value:"
read *, value
end function
subroutine while_loop(start, stop, increment)
integer :: start, stop, increment
integer :: count
print ("(/ a i2 a i2 a i2 a)"), &
"While loop counting from ", start, &
" to ", stop, " by ", increment, ":"
count = start
do while (count <= stop)
print ("(i2)"), count
count = count + increment
end do
end subroutine
subroutine do_loop(start, stop, increment)
integer :: start, stop, increment
integer :: count
print ("(/ a i2 a i2 a i2 a)"), &
"Do loop counting from ", start, &
" to ", stop, " by ", increment, ":"
count = start
do
print ("(i2)"), count
count = count + increment
if (.not. count <= stop) then
exit
end if
end do
end subroutine
subroutine for_loop(start, stop, increment)
integer :: start, stop, increment
integer :: count
print ("(/ a i2 a i2 a i2 a)"), &
"For loop counting from ", start, &
" to ", stop, " by ", increment, ":"
do count = start, stop, increment
print ("(i2)"), count
end do
end subroutine
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own Fortran compiler / interpreter / IDE.