Monday, October 26, 2015

test 9 corrections

2)Consider the following code fragment:
int[] r = { 9, 2, 4, 3, 7, 5, 0, 1 };
for ( int t : r )
{
  t = t + 1;
}
Value: 1 point.
Which of the following is a true statement?
  1. The code will execute and the elements of the array r will be unchanged.
  2. The code will execute and each element of the array r will be incremented.
  3. The code will execute and each element of the array r will be the sum of the previous elements.
  4. The code will execute and each element t of the array r will be the sum of the first t integers.
  5. 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).

2 comments:

  1. Did you try running the code to see what happens?

    Here 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]

    ReplyDelete
  2. There is a really important concept here - an iterator. See:

    https://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.

    ReplyDelete