Suppose we have a set of non-negative input integers terminated with a negative value. These input values are on separate lines. Write a program to determine the number of input data items, excluding the negative one at the end, and compute the minimum and the maximum. For example, the following input contains 7 data values with the seventh being negative. Of the six non-negative ones, the minimum and maximum are 2 and 9, respectively.
5 3 9 2 7 4 -1
! ------------------------------------------------------
! This program reads in a number of integer input until
! a negative one, and determines the minimum and maximum
! of the input data values.
! ------------------------------------------------------
PROGRAM MinMax
IMPLICIT NONE
INTEGER :: Minimum, Maximum ! max and min
INTEGER :: Count ! # of data items
INTEGER :: Input ! the input value
Count = 0 ! initialize counter
DO ! for each iteration
READ(*,*) Input ! read in a new input
IF (Input < 0) EXIT ! if it is < 0, done.
Count = Count + 1 ! if >= 0, increase counter
WRITE(*,*) 'Data item #', Count, ' = ', Input
IF (Count == 1) THEN ! is this the 1st data?
Maximum = Input ! yes, assume it is the
Minimum = Input ! min and the max
ELSE ! no, not the 1st data
IF (Input > Maximum) Maximum = Input ! compare against the
IF (Input < Minimum) Minimum = Input ! existing min & max
END IF
END DO
WRITE(*,*)
IF (Count > 0) THEN ! if at one data item found
WRITE(*,*) 'Found ', Count, ' data items'
WRITE(*,*) ' Maximum = ', Maximum
WRITE(*,*) ' Minimum = ', Minimum
ELSE
WRITE(*,*) 'No data item found.' ! no data item found
END IF
END PROGRAM MinMax
Click here to download this program.
Data item #1 = 5 Data item #2 = 3 Data item #3 = 9 Data item #4 = 2 Data item #5 = 7 Data item #6 = 4 Found 6 data items Maximum = 9 Minimum = 2