+ 1
Can someone explain? C#
I met this code by doing challenges, can someone explain how is this possible that b = 5? int a = 0; int b = 0; while(a<3) { ++a; a*=a; b+=a; } Console.Write(b); //output: 5
4 Answers
+ 9
1st iteration:
0<3
++a, a=1
a*=a, a=1
b+=a, b=1
2nd iteration:
1<3
++a, a=2
a*=a, a=4
b+=a, b=1+4, b=5
3rd iteration:
4<3 false, end of while loop
Console.Write(b) , output is 5
+ 1
maksonios The loop round 2 times..
1 time,
Outside loop a = 0
Inside loop ++a//(a=1)
a*=a//(a=1)
b+=a//(b=0+1=1)
2 time,
Outside loop a = 1
Inside loop ++a//(a=2)
a*=a//(a=4)
b+=a//(b=4+1=5)
//loop finish.
Output b= 5
+ 1
Thanks a lot guys, now I understand how while and for works