Computer Science 1
Top Lectures Assignments Noticeboard

Designing loops


Reading: Chapter 9.1-9.3.11

Multiplication

Say there was no multiplication operations, and we needed to write a method to provide this operation:
private int multiply (int x, int y) {...}

Informal procedure

Choosing and defining variables

Skeleton of the code

The while condition

Initialization

Guaranteeing termination

Completing the loop body

Initialization again

private int multiply (int x, int y) {
  int count; // count == the number of additions done
  int result; // result == 0 + x + x + ... + x, i.e., result == x * count
  count = 0;
  result = 0;
  while (count != y) {
    result += x;
    count += 1;
  }
  return result;
}

Last modified: 3/29/99