8. 조건문 (The if statements)
어떠한 프로그램 언어에서든지 중요한 것이 조건문onditional
statements이다. Fortran에서 가장 공통인 조건문은
if문인데 실제로는 여러 가지 형태이다.
가장 간단한 문장은 논리 if문이다.
if (logical expression) executable statement
이는 한 줄에 적어야 한다. 위 예에서는 x의 절대값을 구하는 것이다.
if (x .LT. 0) x = -x
if 내부에서 한 문장 이상을 수행하여야 할 경우에는 다음의 syntax를 사용한다.
if (logical expression) then
statements
endif
가장 일반적인 if문의 형태는
if (logical expression) then
statements
elseif (logical expression) then
statements
:
:
else
statements
endif
수행 순서는 위에서 아래 방향이다. 조건식은 하나가 참일때 까지 순서대로 그 값을 구한다. 그 후 그와 관련된 code를 수행하고 endif 이후의 다음 문장으로 뛰어 넘는다.
겹쳐진 if 문 (Nested if statements)
if 문은 여러 단계에 걸쳐 겹쳐 쓸 수 있다. 읽기 좋게 하기 위하여 알맞게 들여쓰기하면 좋다.
if (x .GT. 0) then
if (x .GE. y) then
write(*,*) 'x is positive and x >= y'
else
write(*,*) 'x is positive but x < y'
endif
elseif (x .LT. 0) then
write(*,*) 'x is negative'
else
write(*,*) 'x is zero'
endif
너무 여러 단계의 if 문을 겹쳐 쓰면 따라잡기 힘들므로 주의하여야 한다.
Exercises
- Exercise A
- 실수 변수 t에 다음 값을 지정하는 Fortran 77 code를 작성하라. (assume x와 y는 그 전에 정의하였다고 가정한다.)
x+y if x and y are both positive
x-y if x is positive and y negative
y if x is negative
0 if x or y is zero
[Fortran Tutorial]
충남대학교 물리학과 오 병성