UNIHIVE

Study Hub UNIPORT ENG 213.1

ENG 213.1 · Computer Programming for Engineers

Repetition: DO loops

Counted DO loops, DO WHILE, EXIT and CYCLE, accumulating sums, and avoiding endless loops.

Our notes

1 min read

Counted DO loop

do i = start, stop, step
  statements
end do
The step is optional (default 1) and may be negative. The loop variable must be an integer.

Worked example: sum and factorial

program sums
  implicit none
  integer :: i, total, fact
  total = 0
  fact = 1
  do i = 1, 100
    total = total + i
  end do
  do i = 1, 5
    fact = fact * i
  end do
  print *, total, fact
end program sums
Output: 5050 120. Check: 100 × 101 / 2 = 5050; 5! = 120.

DO WHILE

Repeats while a condition is true:
do while (error > tolerance)
  statements that change error
end do

DO with EXIT (general loop)

do
  read *, x
  if (x < 0.0) exit
  total = total + x
end do
exit leaves the loop; cycle skips to the next pass.

Worked example: compound growth until a target

How many years for a ₦100,000 deposit at 10% per year to double?
program double
  implicit none
  real :: amount
  integer :: years
  amount = 100000.0
  years = 0
  do while (amount < 200000.0)
    amount = amount * 1.10
    years = years + 1
  end do
  print *, years, amount
end program double
Output: 8 years, amount about 214,358.88 (after 7 years it is 194,871.71, still short). The interest rate is only an example.

Nested loops

A loop inside a loop: the inner loop runs completely for each pass of the outer loop. Used for tables and two-dimensional arrays.

Accumulators and counters

  • Set a sum to 0 and a product to 1 before the loop.
  • Add or multiply inside the loop.

Endless loops

A DO WHILE whose condition never becomes false never stops. Always change the tested variable inside the loop, and for iterative methods add a maximum number of passes.

Exams usually ask

  • Write a loop to sum a series, build a table or find a maximum.
  • Give the output of a loop by tracing it.

Common mistake

Setting the accumulator to zero inside the loop, so it restarts every pass and only the last value is kept.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All ENG 213.1 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.