Midterm Two Practice Questions
Problem 1: What does the following snippet of code print out to the
console when it runs?
int a = 3, b = 2, c = 3, d = 2;
H.pl(a + " " + b);
H.pl(foo(b));
H.pl(a + " " + b);
H.pl(foo(foo(b)));
H.pl(a + " " + b);
H.pl(c + " " + d);
H.pl(bar(c));
H.pl(c + " " + d);
H.pl(bar(bar(c)));
H.pl(c + " " + d);
where foo and bar are defined as follows:
public static int foo(int a) {
return 2 * a;
}
public static int bar(int c) {
int d;
d = 2 * c;
c = -3
return c;
}
Problem 2: What will does the following snippet of code print out to the
console when it runs?
int [] a = {3,6,0,4,1};
int tmp, p = 0;
for (int i = 1; i < a.length; i++)
if( a[i] <= a[0] ) {
p++;
tmp = a[p];
a[p] = a[i];
a[i] = tmp;
}
H.p("a = ");
for(int i = 0; i < a.length; i++)
H.p(a[i] + " ");
H.pl();
int [] b = {3,0,7,0,1};
int j = 4;
for(int i = 4; i >= 0; i--) {
if(b[i] != 0) {
b[j] = b[i];
if(i != j)
b[i] = 0;
j--;
}
}
H.p("b = ");
for(int i = 0; i < b.length; i++)
H.p(b[i] + " ");
H.pl();
Problem 3: Write a method that takes in an array of integers and returns
an array of integers that contains the values of those integers in the original array
that are strictly larger than val.
You should use the following signature:
public static int [] make_array(int [] a, int val)
For instance, if you used this method as follows:
int [] data = {3,5,-1,-7,2,4,1,7};
int [] new_data = make_array(data,2);
then new_data would contain the values {3,5,4,7}.
Problem 4: What will main print to the console when it runs?
class CS5App {
public static void main(String [] args) {
int c = 10;
int [] d = {32,5,-1};
double e = mystery(c,d);
H.p("c = " + c + " and d = ");
for(int i = 0; i < d.length; i++)
H.p(d[i] + " ");
H.pl(" e = "+e);
}
public static double mystery(int a, int [] b) {
b[0] = a / 10;
a = (a + 5)%a;
H.p("a = " + a + " and b = ");
for(int i = 0; i < b.length; i++)
H.p(b[i] + " ");
H.pl();
return ((double)b[1])/(a+5*b[0]);
}
}