Repetition (While Loop) LAB 9 ICS 101 Lab Hossain Arif ICS Dept
Repetition DO Loops Last LAB WHILE Loops This LAB
WHILE Loop Informal representation WHILE condition EXECUTE THE following BLOCK OF STATEMENTS FORTRAN does not have explicit WHILE statement
WHILE Loop WHILE Loop can be written as follows: n IF (condition) THEN Block of statements GOTO n ENDIF
Example Consider this program – calculates average of 6 numbers REAL X1, X2, X3, X4, X5, X6 REAL SUM, AVG READ*, X1 READ*, X2 READ*, X3 READ*, X4 READ*, X5 READ*, X6 SUM = X1 + X2 + X3 + X4 + X5 + X6 AVG = SUM / 6.0 PRINT*, AVG END
Example (Cont) Using WHILE loop REAL X REAL SUM, AVG INTEGER K 15 IF ( K .LT. 6 ) THEN READ*, X SUM = SUM + X K = K + 1 GOTO 15 ENDIF AVG = SUM / 6.0 PRINT*, AVG END
Example(2) REAL WEIGHT READ*, WEIGHT 11 IF ( WEIGHT .NE. -1.0 ) THEN IF ( WEIGHT .LT. 0 .OR. WEIGHT .GE. 400 ) THEN PRINT*, ‘Weight is OUT of range’ ELSEIF ( WEIGHT .LT. 65 ) THEN PRINT*, ‘LIGHT-WEIGHT’ ELSEIF ( WEIGHT .LT. 85 ) THEN PRINT*, ‘MIDDLE-WEIGHT’ ELSE PRINT*, ‘HEAVY-WEIGHT’ ENDIF GOTO 11 END
Nested WHILE Loops WHILE Loops can be nested Inner loop must start after outer loop and must finish before it You can have as many nested loops as needed
Implied Loops Used in READ and PRINT statements Implied Loop can be written as follows: READ*, (list of variables, index = initial, limit, increment) PRINT*, (list of expressions, index = initial, limit, increment) The same DO loops rules are applied
Implied Loop Example What will printed by this line: PRINT*, (K, K = 1, 10, 1) Output: 1 2 3 4 5 6 7 8 9 10
Exercise(1) Using While loop, write a FORTRAN program that calculates the summation of all odd numbers less than or equal to NUM 1 + 3 + 5 + … + NUM Ask the user for the value of NUM.