sunfresh

Arrays containing 11

Jan 20th, 2023
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. Arrays containing 11
  2. Given an array of ints, compute recursively the number of times that the value 11 appears in the array.
  3.  
  4. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.
  5.  
  6. Input
  7. On the first line you will be given the comma separated array. On the second line you will receive the index.
  8.  
  9. Output
  10. On the only output line you should print the result.
  11.  
  12. Sample tests
  13. Input
  14. 1,2,11
  15. 0
  16. Output
  17. 1
  18. Input
  19. 11,11
  20. 0
  21. Output
  22. 2
  23.  
  24. import java.util.Scanner;
  25.  
  26. public class ArraysContaining11 {
  27. public static void main(String[] args) {
  28. Scanner scanner = new Scanner(System.in);
  29. String[] input = scanner.nextLine().split(",");
  30. int index = Integer.parseInt(scanner.nextLine());
  31. int[] numbers = new int[input.length];
  32.  
  33. for (int i = 0; i < input.length; i++) {
  34. numbers[i] = Integer.parseInt(input[i]);
  35. }
  36. System.out.println(isEleven(numbers, index));
  37.  
  38. }
  39. public static int isEleven(int[] numbers, int index){
  40. int count = 0;
  41. if(index<numbers.length){
  42. if(numbers[index] == 11){
  43. count++;
  44. return count + isEleven(numbers, index+1);
  45. }
  46. return count+isEleven(numbers, index+1);
  47. }
  48. return count;
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment