/* Java class that includes a method for computing the product of ** two integers using repeated addition. The point is to illustrate ** the development of a loop that conforms to a proposed loop invariant. ** ** Authors: R. McCloskey and < STUDENTS' NAMES > */ public class Multiply { /* Given two integers (the first necessarily nonnegative), returns their ** product. Using the multiplication operator is forbidden (except in ** assert statements). ** The intended solution is to be based upon the fact that multiplication ** is repeated addition. That is, the product of k and m is the sum ** m + m + m + ... + m, where m occurs k times. ** pre: k >= 0 ** post: value returned is k*m */ public static int productOf(int k, int m) { int result = ??; int i = ??; assert result == i*m; // Loop invariant verification (after initialization) while (i != k) { result = ?? i = i+1; assert result == i*m; // verify the loop invariant at end of each iteration } // Verify that, upon termination of the loop, 'result' has the // value that is intended to be returned (namely the product k*m). assert result == k*m; return result; } /* This method expects to receive two arguments, both describing ** integers, the first being nonnegative. It calls the productOf() ** method to compute their product and reports the results. */ public static void main(String[] args) { // Translate the two arguments from Strings into values of type int. int first = Integer.parseInt(args[0]); int second = Integer.parseInt(args[1]); // Call productOf() to compute the product and then report the result. int product = productOf(first, second); System.out.printf("productOf(%d,%d) evaluates to %d\n", first, second, product); } }