CS201 Review
Q1: http://codingbat.com/prob/p135988
public class array11{
public static int array11(int[] nums, int index){
int k = 0;
if (nums[index] == 11){
k += 1;
}
// base case
if (index == nums.length-1){
return k;
} else {
// recursive step
return k + array11(nums, index+1);
}
}
public static void main(String[] args){
int[] a = { 11, 12, 15, 5, 11, 17 };
System.out.println(array11(a, 0));
}
}
Q2: http://codingbat.com/prob/p170924
public class replace_pi{
public static String[] replace(String[] a, int index){
// checks for pi, changes to 3.14
if (a[index].equals("pi")){
a[index] = "3.14";
}
// base case
if (a.length-1 == index){
return a;
} else {
// recursive step
return replace(a, index+1);
}
}
public static void main(String[] args){
// initial array
String[] a = { "pi", "apple_pie", "banana_pie", "pi", "pip", "orange_juice" };
// changed array
a = replace(a, 0);
// start creating suitable string representation
String strng = "{ ";
for (int i = 0; i < a.length; i++){
strng += (a[i] + ", ");
}
// replaces last ',\ '
strng = strng.substring(0, strng.length() -2);
strng += " }";
System.out.println(strng);
}
}
Comments