Given a set of integer input values, write a program to count the number of positive and negative values and compute their sums.
The input is organized as follows:
7 -6 7 2 -9 0 8 0
Click here to download this program.! --------------------------------------------------------- ! This program counts the number of positive and negative ! input values and computes their sums. ! --------------------------------------------------------- PROGRAM Counting IMPLICIT NONE INTEGER :: Positive, Negative INTEGER :: PosSum, NegSum INTEGER :: TotalNumber, Count INTEGER :: Data Positive = 0 ! # of positive items Negative = 0 ! # of negative items PosSum = 0 ! sum of all positive items NegSum = 0 ! sum of all negative items READ(*,*) TotalNumber ! read in # of items DO Count = 1, TotalNumber ! for each iteration READ(*,*) Data ! read an item WRITE(*,*) 'Input data ', Count, ': ', Data IF (Data > 0) THEN ! if it is positive Positive = Positive + 1 ! count it PosSum = PosSum + Data ! compute their sum ELSE IF (Data < 0) THEN ! if it is negative Negative = Negative + 1 ! count it NegSum = NegSum + Data ! compute their sum END IF END DO WRITE(*,*) ! display results WRITE(*,*) 'Counting Report:' WRITE(*,*) ' Positive items = ', Positive, ' Sum = ', PosSum WRITE(*,*) ' Negative items = ', Negative, ' Sum = ', NegSum WRITE(*,*) ' Zero items = ', TotalNumber - Positive - Negative WRITE(*,*) WRITE(*,*) 'The total of all input is ', Positive + Negative END PROGRAM Counting
will generate the following output:count < data.in
Input data 1: -6 Input data 2: 7 Input data 3: 2 Input data 4: -9 Input data 5: 0 Input data 6: 8 Input data 7: 0 Counting Report: Positive items = 3 Sum = 17 Negative items = 2 Sum = -15 Zero items = 2 The total of all input is 5
This loop iterates TotalNumber times. For each iteration, it reads in a new data into Data. The IF-THEN-ELSE-END IF statement tests to see if it is positive or negative, adds 1 into the corresponding counter, and adds the value into the corresponding sum. Note that the number of zero items are not counted, since TotalNumber - Positive - Negative gives the number of zero items. The sum of all zero items are not calculated either, since it must be zero!