Java Practice Solutions
Java Practice Solutions
Java Practice Solutions
(a)
11011
(b)
11210
(c)
11222
(d)
11235
(e)
11248
(7)
Given
double x = 5, y = 2;
What
is
the
value
of
m
after
the
following
statement
is
executed?
int m = (int)(x + y + x / y - x * y - x / (10 * y));
(a)
-‐1
(b)
-‐0.75
(c)
-‐0.5
(d)
0
(e)
1
(8)
What
is
the
value
of
sum
after
the
following
code
segment
is
executed?
int p = 3, q = 1, sum = 0;
while (p <= 10) {
sum += p % q;
p++;
q++;
}
(a)
0
(b)
10
(c)
12
(d)
14
(e)
52
(9)
Consider
the
following
method:
THIS
TOPIC
NOT
COVERED
IN
CLASS
–
PLEASE
IGNORE
public int goFigure(int x) {
if (x < 100)
x = goFigure(x + 10);
return (x - 1);
}
What
does
goFigure(60)
return?
(a)
59
(b)
69
(c)
95
(d)
99
(e)
109
(10)
What
are
the
values
of
m
and
n
after
the
following
code
runs?
int m = 20, n = 2, temp;
printNumbers(num);
}
n = 6
return arr;
}
(3)
Write
a
method
named
minGap
that
accepts
an
integer
array
as
a
parameter
and
returns
the
minimum
'gap'
between
adjacent
values
in
the
array.
The
gap
between
two
adjacent
values
in
a
array
is
defined
as
the
second
value
minus
the
first
value.
For
example,
suppose
a
variable
called
array
is
an
array
of
integers
that
stores
the
following
sequence
of
values.
int[] array = {1, 3, 6, 7, 12};
The
first
gap
is
2
(3
-‐
1),
the
second
gap
is
3
(6
-‐
3),
the
third
gap
is
1
(7
-‐
6)
and
the
fourth
gap
is
5
(12
-‐
7).
Thus,
the
call
of
minGap(array)
should
return
1
because
that
is
the
smallest
gap
in
the
array.
Notice
that
the
minimum
gap
could
be
a
negative
number.
For
example,
if
array
stores
the
following
sequence
of
values:
{3,
5,
11,
4,
8}
The
gaps
would
be
computed
as
2
(5
-‐
3),
6
(11
-‐
5),
-‐7
(4
-‐
11),
and
4
(8
-‐
4).
Of
these
values,
-‐7
is
the
smallest,
so
it
would
be
returned.
This
gap
information
can
be
helpful
for
determining
other
properties
of
the
array.
For
example,
if
the
minimum
gap
is
greater
than
or
equal
to
0,
then
you
know
the
array
is
in
sorted
(nondecreasing)
order.
If
the
gap
is
greater
than
0,
then
you
know
the
array
is
both
sorted
and
unique
(strictly
increasing).
If
you
are
passed
an
array
with
fewer
than
2
elements,
you
should
return
0.
private static int minGap(int[] value) {
if (value.length < 2)
return 0;
int min = value[1]-value[0];
for(int i=1;i<value.length-1;i++)
if(min>value[i+1]-value[i])
min = value[i+1]-value[i];
return min;
}
(4)
Write
a
method
named
toBinary
that
accepts
an
integer
as
a
parameter
and
returns
a
string
of
that
number's
representation
in
binary.
For
example,
the
call
of
toBinary(42)
should
return
"101010".
We
will
assume
a
positive
parameter.
private static String toBinary(int num) {
if (num == 0)
return "0";
String str="";
while (num != 0) {
str = (num%2)+str;
num /= 2;
}
return str;
}