int[] r = { 9, 2, 4, 3, 7, 5, 0, 1 };
for ( int t : r )
{
t = t + 1;
}
for ( int t : r )
{
t = t + 1;
}
Which of the following is a true statement?
- The code will execute and the elements of the array r will be unchanged.
- The code will execute and each element of the array r will be incremented.
- The code will execute and each element of the array r will be the sum of the previous elements.
- The code will execute and each element t of the array r will be the sum of the first t integers.
- The code will generate an error.
I got this wrong because I chose 2 believing that changing t would change the array that was incorrect. thus array r would not be changed therefore the answer would be 1.
3)what is output by the following code fragment? (You may assume that the for-each loop references the array elements in index order.) String[] p = { "A", "B", "C", "D" };
String b = "";
for ( String q : p )
b = q + b;
System.out.println( b )
7) I got this wrong because I forgot that q+b is diffrent from b+q and beleved that adding onto a string always happened at the end. in hindsight it was kind of a silly mistake the real answer I should have got was DCBA.
What can be said about the value of d after the comment is replaced by an actual initialization statement and the resulting code is executed? String[] a;
// code to initialize a
boolean d = false;
for ( String b : a )
{
for ( String c : a )
{
if ( b.equals( c ) )
d = true;
}
}
I got this wrong because I neglected to test the code if a had nothing in it and thus I missed that a is false if there is nothing in the list. believing that anything I entered in for a would output true I answered A when in reality it was B (The value is true if a contains at least one element; otherwise it is false).
Did you try running the code to see what happens?
ReplyDeleteHere is a Python version:
r = [9, 2, 4, 3, 7, 5, 0, 1]
for t in r:
t += 1
print(t)
print(r)
Running it gives:
10
3
5
4
8
6
1
2
[9, 2, 4, 3, 7, 5, 0, 1]
There is a really important concept here - an iterator. See:
ReplyDeletehttps://en.wikipedia.org/wiki/Iterator
Try this on Monday:
r = [9, 2, 4, 3, 7, 5, 0, 1]
x = iter(x)
t = x.__next__()
while t:
t = t + 1
print(t)
t = x.__next__()
print(t)
print(r)
Let me know if that helps you understand what is going on better. If not, I'll explain it on Wednesday.