Max Score = 78 + 7 (10% for programming style) = 85 Take two

advertisement
Max Score = 78 + 7 (10% for programming style) = 85
1. Take two integer parameters and return the larger.
public static int larger(int x, int y)
{
if (x > y)
return x;
else
return y;
}
[5 points]
2. Take three parameters: an integer array list and two integers i and j, and swap a[i] and a[j]. This
requires only three lines of code in addition to the method header.
public static void swap(int[] list, int i, int j)
{
int temp = list[i];
list[i] = list[j];
list[j] = temp;
}
[10 points]
3. Take one parameter, an integer array, and return the index of the smallest value in the array. If the
smallest value occurs more than once, return the index of the leftmost occurrence.
public static int smallestIndex(int[] list)
{
int smallestIndexSoFar = 0;
for (int i=1; i<list.length; i++)
{
if (list[i] < list[smallestIndexSoFar])
smallestIndexSoFar = i;
}
return smallestIndexSoFar;
}
[15 points]
4. Take a String parameter and return a String that is the same as the parameter, except that leading and
trailing blanks have been removed. So, for example, if the parameter is " 123 ", then the returned
value is "123".
public static String stripBlanks(String s)
{
// Remove leaning blanks.
while (s.length()>0 && s.charAt(0)==' ')
{
s = s.substring(1,s.length());
}
if (s.length()==0)
return s;
// Remove trailing blanks.
while (s.charAt(s.length-1)==' ')
{
s = s.substring(0,s.length()-1);
}
return s;
// SC eval
}
[20 points]
5. Take an integer array parameter and return the average of the elements.
public static double averageArray(int[] a)
{
int sum = 0;
for (int i=0; i < a.length; i++)
{
sum = sum + a[i];
}
return (double)sum/a.length;
}
[14 points]
6. Take an integer array parameter and return true if the array is sorted in non-decreasing order left to
right. Non-decreasing order implies that every element is either greater than or equal to the previous
element in the array.
public static boolean allPos(int[] a)
{
for (int i=0;i < a.length-1; i++) // Notice the -1
{
if (a[i] > a[i+1]) // Not sorted
return false;
}
return true;
}
[14 points]
Download