An unstructured do loop does not have a built-in condition check,
but uses if and exit to exit
the loop when some condition is met. The do
loop itself is equivalent to do while ( .true. ).
Example 20.3. Unstructured Fortran Loop
module constants
double precision, parameter :: PI = 3.1415926535897932d0
end module constants
program angles
use constants ! Constants defined above
! Disable implicit declarations (i-n rule)
implicit none
! Variable definitions
integer :: angle
! Statements
angle = 0
do
! Body
print *, 'sine(',angle,') = ', sin(angle * PI / 180.0d0)
! Housekeeping and condition
angle = angle + 1
if ( angle > 360.0d0 ) exit
enddo
end program
The advantage of an unstructured do loop is that the condition can be checked anywhere within the body of the loop. Structured loops always check the condition at the beginning or end of the loop. The down side to unstructured do loops is that they are unstructured. They require less planning (design) before implementation, which often leads to messier code that can be harder to follow.
Like Fortran's exit statement, the C
break statement immediately terminates the current
loop so the program continues from the first statement after the
loop.
Unlike Fortran, C does not have a unstructured loop construct,
so use of break is never necessary. Well-structured
code will generally use the loop condition to terminate the loop,
and an if statement to trigger a break
would be redundant. However, we can create an unconditional
loop like Fortran's unstructured do loop using
while ( true ):
Example 20.4. Unstructured C Loop
#include <stdio.h>
#include <math.h>
#include <stdbool.h> // Define "true" constant
int main()
{
int angle;
angle = 0;
while ( true )
{
printf("sine(%d) = %f\n", angle, sin(angle * M_PI / 180.0));
if ( ++angle > 359.0 ) break;
}
return 0;
}
Write a C or Fortran program using that prints the square
root of every number
entered by the user until they enter a sentinel value of
-1. Use a C break or a Fortran
exit to terminate the loop.
Please enter an integer, or -1 to quit.
4
sqrt(4) = 2.000000
Please enter an integer, or -1 to quit.
9
sqrt(9) = 3.000000
Please enter an integer, or -1 to quit.
10
sqrt(10) = 3.162278
Please enter an integer, or -1 to quit.
-1