isefire

CS201 Review Session

Oct 28th, 2015
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | None | 0 0
  1. CS201 Review
  2.  
  3. Q1: http://codingbat.com/prob/p135988
  4.  
  5. public class array11{
  6.     public static int array11(int[] nums, int index){
  7.     int k = 0;
  8.     if (nums[index] == 11){
  9.         k += 1;
  10.     }
  11.     // base case
  12.     if (index == nums.length-1){
  13.         return k;
  14.     } else {
  15.         // recursive step
  16.         return k + array11(nums, index+1);
  17.     }
  18.  
  19. }
  20.  
  21.     public static void main(String[] args){
  22.         int[] a = { 11, 12, 15, 5, 11, 17 };
  23.         System.out.println(array11(a, 0));
  24.     }
  25. }
  26.  
  27. Q2: http://codingbat.com/prob/p170924
  28.  
  29. public class replace_pi{
  30.    
  31.     public static String[] replace(String[] a, int index){
  32.        
  33.         // checks for pi, changes to 3.14
  34.         if (a[index].equals("pi")){
  35.             a[index] = "3.14";
  36.         }
  37.        
  38.         // base case
  39.         if (a.length-1 == index){
  40.             return a;
  41.         } else {
  42.             // recursive step
  43.             return replace(a, index+1);
  44.         }
  45.     }
  46.    
  47.     public static void main(String[] args){
  48.         // initial array
  49.         String[] a = { "pi", "apple_pie", "banana_pie", "pi", "pip", "orange_juice" };
  50.         // changed array
  51.         a = replace(a, 0);
  52.        
  53.         // start creating suitable string representation
  54.         String strng = "{ ";
  55.         for (int i = 0; i < a.length; i++){
  56.             strng += (a[i] + ", ");
  57.         }
  58.         // replaces last ',\ '
  59.         strng = strng.substring(0, strng.length() -2);
  60.         strng += " }";
  61.         System.out.println(strng);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment