Search code examples
if-statementfortrando-loops

Output the corresponding value as well for the other chosen value (DO Loops)


PROGRAM ONE

REAL:: num1 = 200,num2 = 16,num3 = 10,num4
REAL:: counter,smallest

WRITE(*,*) "    Counter", "     num4"
WRITE(*,*) "    --------------------"
DO counter = 0.1,8,0.1
  num4 = (num1 * num2 * num3)/(counter * sqrt(num3**2 - counter**2))
  WRITE(*,*) counter,num4

  IF (counter == 0.1) THEN
     smallest = num4
  END IF

  IF (num4 < smallest) THEN
     smallest = num4
  END IF  

END DO
WRITE(*,*) "The smallest num4 is:", smallest

STOP
END PROGRAM ONE

The program needs to be ran to understand what I am trying to say.

This finds and displays the lowest num4 value. What I also do want it to display is the corresponding counter value to the num4 value. That counter value will go along with the last WRITE statement. It should say:

WRITE(*,*) "The smallest num4 is:", smallest, "for", counter

The output should be:

The smallest num4 is 640.021 for 7.10000

Solution

  • Declare a new variable to save off the counter value that corresponds to the smallest value of num4.

    So near the top of your program have:

    REAL:: counter,smallest,smallCtr
    

    and then set that in the IF blocks when you assign to smallest:

    IF (counter == 0.1) THEN
      smallest = num4
      smallCtr = counter
    END IF
    
    IF (num4 < smallest) THEN
      smallest = num4
      smallCtr = counter
    END IF
    

    and then you can write it out along with smallest:

    WRITE(*,*) "The smallest num4 is:", smallest, "for", smallCtr