About Question enthuware.ocajp.i.v7.2.960 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
disznoperzselo
Posts: 28
Joined: Fri Jan 02, 2015 12:13 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.960 :

Post by disznoperzselo »

It is easy if you try to apply highschool mathematics.
As a first step understand what the innermost loop does:

Code: Select all

 
for(int k = 0; k < 3; k++){ 
   c++;  
   if(k>j)
     break; 
}
Clearly, it increments c with the following sum:

Code: Select all

 
sum{ 1: 0 <=  k < = j + 1}  =  j + 2
 
Now, you have to run the refactored nested loops in your head :)
- or sum it up using an equivalent math formula -

Code: Select all

  
for(int i = 0; i < 2; i++){
   for(int j = 0; j < 2; j++){ 
        c += j + 2;
   }
}
That is

Code: Select all

sum { j + 2 :  j = 0,1}  =  5 
c = sum { 5 : i = 0,1 } = 10.

EelcoD
Posts: 10
Joined: Sat Jan 24, 2015 8:09 am
Contact:

Re: About Question enthuware.ocajp.i.v7.2.960 :

Post by EelcoD »

I did it this way:
If you leave out the break-statement, the "c++" statement is executed 12 times (3x2x2).

Quickly write down all the loops:
i-j-k
1) 0-0-0
2) 0-0-1
3) 0-0-2
4) 0-1-0
5) 0-1-1
6) 0-1-2
7) 1-0-0
8) 1-0-1
9) 1-0-2
10) 1-1-0
11) 1-1-1
12) 1-1-2

As soon as (k>j) the next loop (if any) is not executed.

Above this means that the loop 3) is not executed, since loop 2) already satisfied the condition.
Loop 9) is also not executed, since loop 8) already satisfied the condition.

I hope this helps anyone.

JuergGogo
Posts: 28
Joined: Mon Sep 25, 2017 8:16 am
Contact:

Re: About Question enthuware.ocajp.i.v7.2.960 :

Post by JuergGogo »

The tip of computerinfoscience works fine.
As a first step forget about the outer loop A, since it has no effect on the if-break statement. So the question is reduced to two nested loops which can be analyzed easily. --> c=5
At the end double c *= 2 since Loop A runs twice. --> c=10

RobinDRG
Posts: 6
Joined: Sat Jun 23, 2018 10:17 am
Contact:

Re: About Question enthuware.ocajp.i.v7.2.960 :

Post by RobinDRG »

I added an statement in the inner loop to help me understand how it works. Hope help someone else:


i:0 j:0 k:0 C:1
i:0 j:0 k:1 C:2
i:0 j:1 k:0 C:3
i:0 j:1 k:1 C:4
i:0 j:1 k:2 C:5
i:1 j:0 k:0 C:6
i:1 j:0 k:1 C:7
i:1 j:1 k:0 C:8
i:1 j:1 k:1 C:9
i:1 j:1 k:2 C:10
final c= 10

Dreamweaver
Posts: 32
Joined: Mon Dec 29, 2014 4:14 pm
Contact:

Re: About Question enthuware.ocajp.i.v7.2.960 :

Post by Dreamweaver »

I simplify on paper like this:

c = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
i = 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1
j = 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | 1
k = 0 | 0 | 1 | 0 | 1 | 2 | 0 | 1 | 0 | 1 | 2

Post Reply

Who is online

Users browsing this forum: No registered users and 48 guests