In: Computer Science
Hi can someone fully explain how the output was reached?
thanks
public class Example
{
public static void main(String [] args)
{
int a = 0, b = 4, i, j;
for (i = 1; i<=3; i++)
{
for(j = 1; j < 3; ++j)
{
a = a + j;
b = b + a;
System.out.println (a + " " + b);
}
}
System.out.println ("ALL DONE");
}
}
output
1 5
3 8
4 12
6 18
7 25
9 34
ALL DONE
a=0,b=4
Loop: i<=3 means 1<=3 true
loop: j=1 and j<3 means 1<3 true
a=a+j means 0+1 so a=1
b=b+a means b=4+1 = b=5
so it will print 1 5
loop: j<3 means 2<3 true
a=a+j means 1+2 so a=3
b=b+a means b=5+3 = b=8
so it will print 3 8
loop: j<3 means 3<3 false
a=3 and b=8
Loop: i<=3 means 2<=3 true
loop: j=1 and j<3 means 1<3 true
a=a+j means 3+1 so a=4
b=b+a means b=8+1 = b=12
so it will print 4 12
loop: j<3 means 2<3 true
a=a+j means 4+2 so a=6
b=b+a means b=12+6 = b=18
so it will print 6 18
loop: j<3 means 3<3 false
a=6 and b=18
Loop: i<=3 means 3<=3 true
loop: j=1 and j<3 means 1<3 true
a=a+j means 6+1 so a=7
b=b+a means b=18+7 = b=25
so it will print 7 25
loop: j<3 means 2<3 true
a=a+j means 7+2 so a=9
b=b+a means b=25+9 = b=34
so it will print 9 34
loop: j<3 means 3<3 false