HW0B: Basic Java Syntax

Optional

Table of Contents

HW Goals

After class on September 3rd, a few of you asked for additional practice with basic Java programs. Here are a few suggested problems, in order of increasing difficulty. Skip ahead as far as you'd like. No starter files are provided.

For each problem:

Part 1: Max

Write a function max(int[] a) that returns the maximum value of the an int array. Try writing this function using both a while loop and a for loop. See the sidebar for convenient syntax for creating arrays.

Part 2A: 3SUM

Suppose we have an array of integers int[] a. The 3SUM problem asks if there are three integers in a[] such that their sum is zero.

For this problem, write a function threeSum(int[] a) that returns true if there exist three integers in a that sum to zero and false otherwise. Integers may be used more than once. As in part 1, use your main function to perform an ad-hoc test that threeSum works.

For loops will look a lot more compact than while loops for this problem.

Examples:

This might seem daunting at first, but it's relatively straightforward. For a hint, highlight: An alternate way of stating the problem: Do there exist three indices (not necessarily distinct) f, g, and h such that a[f] + a[g] + a[h] == 0?

Part 2B: 3SUM_DISTINCT

Repeat the exercise from Part 2B, but with the constraint that each number can be used only once.

Examples: