Page 1 of 1

About Question com.enthuware.jfcja.v8.2.333 :

Posted: Thu Mar 30, 2023 5:23 pm
by Maria Teresa Lorenzo
Can anybody explain the logic behind this loop?

Thanks

Re: About Question com.enthuware.jfcja.v8.2.333 :

Posted: Thu Mar 30, 2023 5:26 pm
by Maria Teresa Lorenzo
Given the following code, which of these statements are true?

Code: Select all

public class TestClass
{
   public static void main(String args[])
   {
      int k = 0;
      int m = 0;
      for ( int i = 0; i <= 3; i++)
      {
         k++;
         if ( i == 2)
         {
            // line 1
         }
         m++;
      }
      System.out.println( k + ", " + m );
   }
}
These were the 3 possible correct answers:
It will print 3, 2 when line 1 is replaced by break;
It will print 4, 3 when line 1 is replaced by continue.
It will print 3, 3 when line 1 is replaced by i = 4;

Re: About Question com.enthuware.jfcja.v8.2.333 :

Posted: Thu Mar 30, 2023 10:37 pm
by admin
Can you please tell which part do you have trouble understanding? Do you know how break and continue statements work?

In questions like these, you need to keep track of all the variables after each statement. For example, let's see what happens when you put break; in place of //line 1:
In in the first iteration of the for loop, i is 0. Inside the loop, k is incremented to 1, since i is not equal to 2 break is not executed, and then m++ increments m to 1.
In in the second iteration of the for loop, i is 1. Inside the loop, k is incremented to 2, since i is not equal to 2 break is not executed, and then m++ increments m to 2.
In in the third iteration of the for loop, i is 2. Inside the loop, k is incremented to 3, since i is equal to 2 break is executed. Therefore, the loop break (m++ is not executed).

After the for loop, k, which is 3, and m, which is 2, are printed.

You can try doing the same for other two options.