next up previous contents
Next: Repetitive action Up: Controlling the flow of Previous: Conditional execution   Contents

Examples

(Discuss control flow diagram with rombs and rectangles)

if (i .gt. 17) then
   print*, "i > 17 !"
end if

if (i .gt. 17) then
   print*, "i > 17 !"
else
   print*, "i <= 17 !"
end if

if (i .gt. 17) then
   print*, "i > 17 !"
elseif  (i .eq. 17) then 
   print*, "i = 17 !"
elseif  (i .eq. 16) then 
   print*, "i = 16 !"
else
   print*, "i < 16 !"
end if

Example of IF block use: solving a quadratic equation.

program quadratic_eqn_1
implicit none
real::a,b,c ! coeff of the quadratic eqn.
real::d ! determinant
real::x1,x2 ! solutions, if real (cases I, II)
real::xre,xim ! real and imaginary parts of solutions (case III)
!read in the coefficients
print*, 'Please give quadr. eqn. coeff. a, b, c:'
read*,a,b,c
d=b**2-4.0*a*c
! check the cases and treat them seperate
if (d.GT.0.0) then
     x1=(-b-SQRT(d))/(2.0*a)
     x2=(-b+SQRT(d))/(2.0*a)
     print*,'The eqn. has two disctinct real roots: ', &
     'x1=',x1,' x2=',x2
else if(d.EQ.0.0) then
     x1=-b/(2.0*a)
     print*, 'The eqn. has two equal roots: ', &
     'x1=x2=',x1
else ! d<0
     xre=-b/(2.0*a)
     xim=SQRT(-d)/(2.0*a)
     print*, 'The eqn. has two complex-conjugate roots: ',&
     xre,'+/-',xim,'i'
end if
end program quadratic_eqn_1

Example of complex numbers use: solving a quadratic equation, Solution no. 2.

program quadratic_eqn_2
implicit none
real::a,b,c
complex::d,x1,x2,sd
!read in the coefficients
print*,'Please give a, b, c:'
read*,a,b,c
!compute discriminant
d=b**2-4*a*c
!sqrt(d): since d is complex, sqrt is complex
sd=SQRT(d)
! compute roots:
x1=(-b+sd)/(2.0*a)
x2=(-b-sd)/(2.0*a)
print*,'Roots are'
print*,'X1=',x1
print*,'X2=',x2
end program quadratic_eqn_2



Adrian Sandu 2001-08-26