Double Checking the Answer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • javacasper
    New Member
    • Oct 2008
    • 1

    #1

    Double Checking the Answer

    Good evening everyone.

    I came up with the answer 25 for the below question/code. Since J is holding the value of 0 and k = 50, k is greater than 0 thus j + k = 50 and k / 2 is 25. Am I in the ballpark or am I still out in the parking lot on this one?

    Let j and k be two int variables. Trace the execution of the following for loop by showing the values of j and k at the end of each iteration (i.e., immediately after the update part is executed):
    for (j = 0, k = 50; k > 0; j += k)
    k /= 2;
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You're okay on the first iteration. Also, remember how Java rounds (it truncates decimals since k is an int).

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Variable j accumulates the values of k after the loop body has executed and while
      k > 0, so at the end k ends up to be zero because it is divided by two repeatedly
      and j= 12+6+3+1+0

      kind regards,

      Jos

      Comment

      Working...