Study the snippet given below and predict the output
int j,k,p=-1;
for(j=-2;j<=1;j++){
for(k=j;k<=0;k++)
k=Math.max(j*k,p);
System.out.print(k);
p=p+2;
}
Answers
Given:
int j,k,p=-1;
for(j=-2;j<=1;j++)
{
for(k=j;k<=0;k++)
k=Math.max(j*k,p);
System.out.print(k);
p=p+2;
}
Output:
5241
Explanation:
p = -1
For j = -2
k = j = -2
k <= 0 → -2 <= 0 → True
k = Max(j*k,p) = Max((-2)*(-2),-1) = Max(4,-1) = 4
k++ → k = 5
k <= 0 → 5 <= 0 → False
Print(k) → 5
p = p+2 = -1 + 2 = 1
j++ → j = -1
j <= 1 → -1 <= 1 → True
For j = -1
k = j = -1
k <= 0 → -1 <= 0 → True
k = Max(j*k,p) = Max((-1)*(-1),1) = Max(1,1) = 1
k++ → k = 2
k <= 0 → 2 <= 0 → False
Print(k) → 2
p = p+2 = 1 + 2 = 3
j++ → j = 0
j <= 1 → 0 <= 1 → True
For j = 0
k = j = 0
k <= 0 → 0 <= 0 → True
k = Max(j*k,p) = Max((-1)*(0),3) = Max(0,3) = 3
k++ → k = 4
k <= 0 → 4 <= 0 → False
Print(k) → 4
p = p+2 = 3 + 2 = 5
j++ → j = 1
j <= 1 → 1 <= 1 → True
For j = 1
k = j = 1
k <= 0 → 1 <= 0 → False
Print(k) → 1
j++ → j = 2
j <= 1 → 2 <= 1 → False
So, final output is 5241
Given:
int j,k,p=-1;
for(j=-2;j<=1;j++)
{
for(k=j;k<=0;k++)
k=Math.max(j*k,p);
System.out.print(k);
p=p+2;
}
Output:
5241
Explanation:
p = -1
For j = -2
k = j = -2
k <= 0 → -2 <= 0 → True
k = Max(j*k,p) = Max((-2)*(-2),-1) = Max(4,-1) = 4
k++ → k = 5
k <= 0 → 5 <= 0 → False
Print(k) → 5
p = p+2 = -1 + 2 = 1
j++ → j = -1
j <= 1 → -1 <= 1 → True
For j = -1
k = j = -1
k <= 0 → -1 <= 0 → True
k = Max(j*k,p) = Max((-1)*(-1),1) = Max(1,1) = 1
k++ → k = 2
k <= 0 → 2 <= 0 → False
Print(k) → 2
p = p+2 = 1 + 2 = 3
j++ → j = 0
j <= 1 → 0 <= 1 → True
For j = 0
k = j = 0
k <= 0 → 0 <= 0 → True
k = Max(j*k,p) = Max((-1)*(0),3) = Max(0,3) = 3
k++ → k = 4
k <= 0 → 4 <= 0 → False
Print(k) → 4
p = p+2 = 3 + 2 = 5
j++ → j = 1
j <= 1 → 1 <= 1 → True
For j = 1
k = j = 1
k <= 0 → 1 <= 0 → False
Print(k) → 1
j++ → j = 2
j <= 1 → 2 <= 1 → False
So, final output is 5241