5)What is the value of g after the following code is executed?
boolean p = false;
int[] a = { 5, 4, 9, 2, 5, 3, 0, -1 };
int g = 0;
while ( !p && g < a.length )
{
p = ( p || (a[ g ] % 3 == 0) );
g++;
}
int[] a = { 5, 4, 9, 2, 5, 3, 0, -1 };
int g = 0;
while ( !p && g < a.length )
{
p = ( p || (a[ g ] % 3 == 0) );
g++;
}
- 0
- 2
- 3
- 5
- 8
9)What is the value of m after the following code is executed?
int n = 314159;
int m = 0;
while ( n > 0 )
{
m = 10 * m + n % 10;
n /= 10;
}
int m = 0;
while ( n > 0 )
{
m = 10 * m + n % 10;
n /= 10;
}
- 31415.9
- 314159
- 317322713
- 951413
- The program enters an infinite loop and never completes.
10)Recall that, if s and t are Strings, then s.indexOf( t ) returns -1 if t is not a substring of s. However, if t is a substring of s, then s.indexOf( t ) returns the index in s of the first character of the first appearance within s of t. For example,
"abcbcdcde".indexOf( "cd" ) returns 4
"abcbcdcde".indexOf( "dcb" ) returns -1.
"abcbcdcde".indexOf( "dcb" ) returns -1.
Assuming that s and t are Strings, which of the following code fragments are such that the value returned by s.indexOf( t ) before the code is executed is equal to the value of the int n after the code is executed?
- I only
- II only
- III only
- I and II only
- I, II, and III
How is your Python? It would be well worth taking the time to explore this last question further, since it is essentially asking which of these algorithms implement the indexOf method's logic. Here is a little test of all three of them:
ReplyDeletedef index_of_1(t, s):
n = -1
tsize = len(t)
found = False
while not found and tsize <= len(s):
n += 1
if t == s[:tsize]:
found = True
else:
s = s[1:]
if not found:
n = -1
return n
def index_of_2(t, s):
n = -1
ssize = len(s)
tsize = len(t)
found = False
while not found and tsize + n + 1 <= ssize:
n += 1
if t == s[n:n + tsize]:
found = True
if not found:
n = -1
return n
def index_of_3(t, s):
n = 0
ssize = len(s)
tsize = len(t)
found = False
while not found and n + tsize <= ssize:
if t == s[n:n + tsize]:
found = True
n += 1
if found:
n -= 1
else:
n = -1
return n
A good set of tests could be set up to determine if they work as expected. Are you familiar with doctest? If not, let me show it to you this afternoon and ask you to write tests for these.
Ooops, comments don't preserve white space, so the indentation above has been lost. I'll share the source with you in class.
ReplyDelete