001package algs11; 002 003import stdlib.StdOut; 004 005// Homework 2, Parts 2 and 3 (Version 2) 006// 007// Part 1. See MyDebugging.java. 008// 009// Part 2. 010// The motivation for this homework is to help you develop the mental model for how Java 011// functions and loops execute. 012// 013// TODO: Hand-trace the examples given in the main program. There are three of them. 014// You only need to trace the execution of the max method, from the beginning to the end. 015// Be sure to show how each variable changes. You do not need to show line numbers 016// in your traces. 017// 018// Scan your traces and submit them. Or you can do it in ASCII or a Word document. 019// 020// Part 3. 021// Re-write the max function on paper, or in a Word document, using a for loop. 022// 023// TODO: Hand in your new max method with a for loop. 024// 025// Both your traces and your new max method should be in the same file as Part 1. 026// Upload a scan of your handwritten answers or your Word document to D2L. 027// 028// DO NOT TAKE A PICTURE WITH YOUR PHONE. 029// 030// You do not need to hand in this file! 031// 032 033public class MyMaxTrace { 034 public static Double max(double[] a) { 035 if (a.length == 0) { 036 throw new IllegalArgumentException(); 037 } 038 039 // DO NOT change this to "double" with a lower-case "d." 040 Double m = a[0]; 041 int i = 1; 042 while (i < a.length) { 043 if (m < a[i]) { 044 m = a[i]; 045 } 046 i += 1; 047 } 048 return m; 049 } 050 051 public static void testMax(double expected, double[] a) { 052 Double actual = max(a); 053 if (expected != actual) { 054 StdOut.format("max failed: Expecting [%d] Actual [%d] with argument %s\n", expected, actual, java.util.Arrays.toString(a)); 055 } 056 } 057 058 public static void main(String[] args) { 059 // Test 1 060 testMax(31, new double[]{11, 21, 31}); 061 062 // Test 2 063 testMax(31, new double[]{31, 11, 21}); 064 065 // Test 3 066 testMax(81, new double[]{21, 31, 11, 71, 51, 81, 41}); 067 } 068}