None of the three segments will work properly. Each segment has an int[] array a with a length of n. The int value k is equivalent to n. Each statement contains, at one point, the command “a[k] = ”. However, a starts at the 0th element, and thus, doesn’t have a kth element. This will throw an ArrayListOutOfBoundsException; thus, none of the three segments will work properly.
−Phoenix
Create a sampling of this code that you can run through the compiler and debug each case. Revise when able.
ReplyDeleteOf the three, only option 3 will work properly. Option 1 tests if the first number is even, and immediately prints it if it is, then repeats via recursion. This will result in all even numbers being written, but in ascending order; thus, option 1 doesn’t work. Option 2 tests if the first number is even, and will only continue to test numbers if it is. As soon as an odd number is typed, all numbers inserted are repeated backwards. This will result in only the first continuous set of even numbers (and one odd number) to be printed in descending order; thus, option 2 doesn’t work either. Finally, option 3 will repeat as soon as the first number is inserted via recursion. When the “SENTINEL” value (−777) is inserted, each number is analyzed and printed if even. This will result in all even numbers being written in descending order; this, option 3 will work.
ReplyDelete−Phoenix