All Computer Science Resources
Example Questions
Example Question #1 : Iterations
public static boolean remove(int[] arr, int val) {
boolean found = false;
int i;
for(i = 0; i < arr.length && !found; i++) {
if(arr[i] == val) {
found = true;
}
}
// START
if(found) {
for(int j = i; j < arr.length;j++) {
arr[j - 1] = arr[j];
}
arr[arr.length - 1] = 0;
}
// END
return found;
}
What does the code between // START
and // END
do?
Set the deleted index's value to 0
Shift the contents of the array
Delete the values in the array
None of the other options
Overwrite the array values with default values
Shift the contents of the array
The easiest way to approach this question is to comment on this line by line. Notice that the condition only works if the given value was found. (This is the use of the boolean found
.) If the desired value has indeed been located, the code then goes through the array, picking up just past the location of the index. (At this point, i
is one past the index of the value to be deleted.) Then, it goes through the code and moves backward the value at each index. In effect, this shifts the content backward, giving the appearance of having performed a deletion. This is done on the line arr[j - 1] = arr[j];
. Finally, at the end, the final index value is set to a default value, namely 0. (This is done on the line arr[arr.length - 1] = 0;
.)
Example Question #2 : Iterations
#include <iostream>
using namespace std;
int main()
{
int i=0;
int sum =0;
for(i;i<4;i+=2)
{
sum=sum+i;
i--;
}
return 0;
}
What is the value of i and sum?
i=5,sum=7
i=3, sum=8
i=4,sum=4
i=3,sum=6
i=4, sum=6
i=3,sum=6
Let's take a look at the declaration of the foor loop. It will run as long at the integer "i" is less than four. It also increases by 2 after each iteration. i+=2 is equivalent to i=i+2.
Now let's look at the contents of the loop itself. The integer "sum" starts at 0 and is added to i at each iteration. After this we see that 1 number is subtracted from i after each iteration. Now after examining the structure of the loop, let's begin to calculate each iteration.
Iteration 1: i=0, sum=0, then i=-1.
Iteration 2: i=1, sum=1, then i=0.
Iteration3: i=2, sum=3, then i=1,
Iteration 4: i=3, sum =6, then i=3.
There is no iteration 5 because "i" can only be less than four to enter the loop, so the program ends there.
i=3, sum=6
Example Question #1 : Iterations
True or False.
This code snippet will iterate 5 times.
ArrayList<String> arrList = new ArrayList<String>();
arrList.add("string0");
arrList.add("string1");
arrList.add("string2");
arrList.add("string3");
arrList.add("string4");
for (int i = 0; i < arrList.size(); i++) {
System.out.println(arrList.get(i));
}
True
False
True
The ArrayList is populated with 5 strings. The for loop will iterate through the ArrayList from position 0 to 4 because once i gets to 5 the loop with exit. 0 to 4 is five iterations. So the answer is true.
Example Question #1 : Iterations
Suppose you have the following code:
public static void main(String[] args) {
int a =2;
if (a%2==0)
System.out.println("Hello World");
else
System.out.println("Hi");
}
If the main method is called, what will be printed?
An error will be thrown
Hello World
Hi
Hello World
Hello World Hi
Hi
Hello World
"Hello World" will be printed, since the first condition is true: 2%2=0, or equivalently 2 is an even number. Once a condition in an if block is executed, the if block is exited. This means that any other elseif or else clauses will not be executed. If a%2==0 were False, then "Hi" would be printed. In no situation would it be possible for both "Hello World" and "Hi" to be printed. Additionally, no errors would be thrown since the syntax is correct and no runtime errors occur.
Example Question #4 : Iterations
Suppose you are given the following lines of code (and x is some initialized integer):
int k = arr.length;
for (int i = -1; i <k-2; i++)
{
if (arr[i+2] < x)
System.out.print("Hello");
}
What is the maximum number of times "Hello" print?
An ArrayIndexOutOfBoundsException will be thrown
k-2
0
k-1
k
k-1
The answer is k-1, where k is the length of the array.
This problem tests the students' understanding of loop itterations. The loop counter begins at -1, but the first element of arr to be accessed is at index=1. Likewise, the loop exits when i<k-2 is no longer true, and the final index of arr to be accessed is at index=k-3+2=k-1, which is the last element of arr. Therefore, we do not get an ArrayIndexOutOfBoundsException because the array is being accessed properly.
Since the (k-1)th element of arr is accessed (the last element) and the 0th element of arr is skipped (the first element to be accessed is at index=1, and arrays are 0 indexed), there are k-1 loop itterations. If all the values in arr do not exceed x, then "Hello" will printed k-1 times.
Example Question #51 : Programming Constructs
int lairotcaf (int n) {
if (n <= 1){
return 1
}
temp = n * lairotcaf(n-1)
return temp;
}
int num;
cin >> num;
if (num >= 0){
lairotcaf(n)
} else {
cout << "must use number greater or equal to zero"< endl;
}
What is returned by lairotcaf(5)
?
In recursion, a value is calculated in reverse until a point at which an answer is defined. From that point, the definition is used to calculate forward, evaluating the other definitions which rely upon that base condition.
Recursive functions must have a test that will halt recursion. If the current state of the recursive function matches the base condition, the recursion should stop. Otherwise, recursion should continue.
In case you did not notice from the backwards-naming scheme, this is a definition for the factorial function. The function will not be called if a negative number is passed. If 0 or 1 is passed, 1 is returned. 0 or 1 is the base condition. If the number is greater than one, a chain of calls to lairotcaf()
will initiate until a base condition is reached.
Once lairotcaf(5)
is expanded, we have:
Example Question #51 : Programming Constructs
Consider the following code:
public static void main(String[] args) {
System.out.println(equation(8));
}
public static int equation(int a) {
if(a <= 5) {
return 12;
}
return equation(a-2) * equation(a-1);
}
What is the output for the code above?
The function equation is a recursive method, meaning that it calls itself. The easiest way to trace a recursive method is to first pay heed to its stopping case. For this, it is:
if(a <= 5) {
return 12;
}
In this case, it returns 12 for any values less that or equal to 5. Now, begin your trace:
equation(8) = equation(6) * equation(7)
equation(7) = equation(5) * equation(6)
equation(6) = equation(4) * equation(5)
Therefore, equation(6) is:
12 * 12 or 144
Thus, we know:
equation(7) = 12 * 144 = 1728
And, equation(8) = 144 * 1728 = 248832
Example Question #52 : Programming Constructs
Which of the following is a recursive factorial function?
Recall that an example of a factorial is:
public long factorial(long a) {
return a * factorial(a-1) * factorial(a-2);
}
public long factorial(long a) {
a * a-1 * a-2 * a-3 * a-4;
}
public long factorial(long a) {
if(a <= 1) {
return 1;
}
return a * factorial(a-1);
}
public long factorial(long a) {
long ret = 1;
for(int i = 2; i < a; i++) {
ret *= i;
}
return ret;
}
None of the others
public long factorial(long a) {
if(a <= 1) {
return 1;
}
return a * factorial(a-1);
}
Recall that a recursive function calls itself. Therefore, you can eliminate several of the answers just by the fact that they are not recursive in nature. (Indeed the one with a loop is a correct computation.) Now, you can think of a factorial like this:
And then...
And so forth.
Thus, you have a stopping case at 1, which is equal to 1. For any other value, you will return a recursive value, namely the parameter a and then the factorial method called with a-1.
Example Question #51 : Program Implementation
Consider the following code:
public static void main(String[] args) {
System.out.println(foo("This is my favorite: Yay for programming!!!"));
}
public static String foo(String s) {
if(!s.equals("")) {
char c = s.charAt(0);
if(c >= 'A' && c <= 'Z') {
return Character.toLowerCase(c) + foo(s.substring(1));
} else if (c >= 'a' && c <= 'z'){
return Character.toUpperCase(c) + foo(s.substring(1));
}
return foo(s.substring(1));
}
return "";
}
What is the output for the main
function above?
tHISISMYFAVORITEyAYFORPROGRAMMING
tHIS IS MYFAVORITE
ThIs iS mY fAvOriTe: YaY fOr PrOgRaMmIng!!!
tHIS IS MY FAVORITE: yAY FOR PROGRAMMING!!!
ThIs iS mY fAvOriTe
tHISISMYFAVORITEyAYFORPROGRAMMING
The foo
method is clearly recursive. Therefore, let's look at our conditions:
If s
is ""
, then the code reaches the base case (at the very end): return "";
Now, for other strings, there are two cases embedded:
c >= 'A' && c <=
'Z'
and c >= 'a' && c <= 'z'
Notice that c
is the first character of the string. So, for these two cases, if the first character is upper case, the function makes it lower, and if it is lower, it makes it upper case. Then, it makes a recursive call to itself, using the remainder of the string after this first character. If neither of those are reached, it just does a call to itself, ignoring the first character. Therefore, this code will "flip" any cases of alphabetic characters but will ignore all other characters. That is why the correct answer is the compressed-looking string: tHISISMYFAVORITEyAYFORPROGRAMMING
Example Question #2 : Recursion
Which of the following is a recursive method for summing the contents of a list of integers? (Choose the best answer.)
public static int val(List ints) {
int ret = 0;
for(int i = 0; i < ints.size(); i++) {
ret += ints.get(i);
}
return ret;
}
public static int val(List ints) {
if(ints.size() == 0) {
return 0;
} else {
return ints.remove(0) + val(ints);
}
}
public int val(List ints) {
return ints.get(0) + val(ints - 1);
}
public static int val(List ints) {
return ints.get(0) + val(ints.subList(1, ints.size()));
}
public static int val(List ints) {
if(ints.size() == 0) {
return 0;
} else {
return ints.get(0) + val(ints.subList(1, ints.size()));
}
}
public static int val(List ints) {
if(ints.size() == 0) {
return 0;
} else {
return ints.get(0) + val(ints.subList(1, ints.size()));
}
}
Recall that a recursive method is one that calls itself, slowly working toward a "base case" at which it terminates. Therefore, you can immediately eliminate the option that has an iterative loop. This is not recursion.
Next, however, there are two methods that have return values:
return ints.get(0) + val(ints.subList(1, ints.size()));
return ints.get(0) + val(ints - 1);
Neither of these will work, for they never terminate. (Well, they terminate, but only with an error!) Also, the second is nonsensical anyway—you cannot subtract 1 from a list as a whole!
Finally, consider the option with a recursive return value of:
return ints.remove(0) + val(ints);
This actually will add the items correctly. However, by removing items from the list, you will thus destroy the list in the course of adding them! Therefore, the remaining option is the best one for this question:
public static int val(List ints) {
if(ints.size() == 0) {
return 0;
} else {
return ints.get(0) + val(ints.subList(1, ints.size()));
}
}