# LAB #4

## Objectives

• Practice more IF statements and input validation
• Learn do-loops
• File I/O
• Log Generation

1. Type the following program exactly as shown:
```! This program generates a table of the square roots of integers
! in a user-specified range.
program squares
implicit none
integer*2 start, finish, i

! ----------------------------------------------Prompt and Input
print*, "Enter the range (two integers) ..."

! ----------------------------------------------Validation & Processing
if (start .GT. finish) then
print*, "Invalid: the start must be less than the end value!"
else if (start .LT. 0) then
print*, "Invalid: the range must not have negative values!"
else
do i = start, finish
write(*,*) i, sqrt(i*1.)
end do
end if

! ----------------------------------------------
end
```
2. Compile the program as you learned in Lab1.

## Questions

1. When run, the program prompts you to specify a range of positive integers by entering two integers, being the beginning and end of the range. You can enter the two end-points by separating them by a space or a comma or by pressing ENTER. Try: 1,20 and examine the output.
2. Re-run the program and test invalid ranges; e.g. -10, 10 or 10,2. Note how the program ends with an error message even though its code flows "smoothly"; without `end` statements in the middle of it.
3. The argument of the square root function looks strange: Why did we have to mutiply i by 1? Experiment then explain.
4. Add the following statement before the prompt but after declarations:
open (unit=50, file='sqroot.txt'). Furthermore, change the first asterisk in the write statement (inside the loop) to 50. These changes cause the output of the write statement to be redirected: Instead of appearing on the screen, it goes to the named disk file. Verify this by viewing the generated sqroot.txt file.
Note:
• You can view the file by issuing the following DOS command: `type sqroot.txt|more`.
• If you prefer to create the file elsewhere on the hard drive; i.e. not in the same directory as the program, prefix the filename by an appropriate path; e.g. 'c:\\sqroot.txt' will store it in the root dirrectory of drive c:. (since the backslash character has a special meaning to this compiler, we type two backslashes to escape the special handling).
5. Restore the program back to screen output and modify it so that the square root appears formatted with only two decimals.
6. Modify the program so that it does not generate any output for integers that are multiples of 5. For example, if the range is 1 to 18, then no lines will be printed for 5, 10 nor 15.

Fall2002/HR