0

Can some please explain this challenge question algothrim to me please

public class Program { public static void main(String[] args) { int n=0; for(int x=1;x<=2;x++){ for(int y=1;y<=3;y++){ n+=2; } } System.out.print(n); } } Why is the output 12

29th Jan 2021, 8:00 AM
George S Mulbah II
George S Mulbah II - avatar
3 Answers
+ 3
FOR LOOP (2 iterations) { . . . FOR LOOP (3 iterations) { } } The inside loop has 3 iterations and the outside loop has 2 iterations Iterations: ---FIRST--- |---Inside Loop---| n = 2 n = 4 n = 6 ---SECOND--- |---Inside Loop---| n = 8 n = 10 n = 12 ___________ >> n = 12
29th Jan 2021, 8:05 AM
noteve
noteve - avatar
+ 3
George S Mulbah Inner loop will work 3 times and outer loop will work 2 times so total will be 2 * 3 = 6 times. Inside inner loop we are adding 2 in n so it will add till 6 times and output will be 12. Explanation already provided by Cyan
29th Jan 2021, 9:16 AM
A͢J
A͢J - avatar
+ 1
Cyan thanks a lot
29th Jan 2021, 8:07 AM
George S Mulbah II
George S Mulbah II - avatar