+ 6

Explain me this code please.

int a=0, b=0; while(a<3) { ++a; a*=a; b+=a; } Console.Write(b);

14th May 2020, 6:40 PM
Mateusz Legend
Mateusz Legend - avatar
9 Respuestas
+ 8
while loop runs till a's value is less than 3 ++a increases value of a Now a is 1 a*=a means a=a*a which is a=1 and then b+=a is b=b+a b=0+1 b=1 again ++a a=2 now a*=a a=2*2 a=4 b=1+4 b=5 now since a is 4 and greater than 3 Loop terminates and 5 is printed
14th May 2020, 6:48 PM
Abhay
Abhay - avatar
+ 3
Abhay And what will be the result if there will be a++ instead of ++a, 0?
14th May 2020, 6:49 PM
Mateusz Legend
Mateusz Legend - avatar
+ 3
I thought i knew the difference between ++i and i++ but i guess not. Well, i need to read and practice more, thanks a lot friend
14th May 2020, 8:14 PM
Mateusz Legend
Mateusz Legend - avatar
+ 3
Thanks a lot i will keep on trying :)
15th May 2020, 6:07 AM
Mateusz Legend
Mateusz Legend - avatar
+ 2
👍👍👍👍👍👍👍👍👍
15th May 2020, 5:38 AM
abdalrahman alhaymouni
abdalrahman alhaymouni - avatar
+ 2
hello, if you alter the code and write a++ it would not affect the output which is (5) a++ and ++a will only differ when you will assign them to a variable thanks!
15th May 2020, 8:01 AM
Ansh Yadav
Ansh Yadav - avatar
+ 1
It will be same ,it doesn't matter here if you increase it's value before or after however if that was something like b=++a then b value would be 1 and a also 1 and If it was b=a++ then b value would be 0 and a also 0 Then a would get incremented immediately after that and a will be 1
14th May 2020, 7:05 PM
Abhay
Abhay - avatar
+ 1
while(a<3) is used to run till the value of a will be less than 3. Initially a=0, b=0 In the first iteration 0 < 3 is satisfied It first checks the condition of the while loop, if it is satisfied it will enter the loop and perform the following steps 1) ++a which is used to increment the value of a (a++ returns the value after it is incremented, while ++a returns the value before it is incremented. There will be no change in this particular code.) So value of a becomes 1 2) a*=a -> a = a * a -> a = 1 * 1 -> a = 1 3) b+=a -> b = b + a -> b = 0 + 1 -> b = 1 In the next iteration, it checks if 1 < 3 which is satisfied. It performs the following steps again 1) ++a Value of a becomes 2 2) a*=a -> a = a * a -> a = 2 * 2 -> a = 4 3) b+=a -> b = b + a -> b = 1 + 4 -> b = 5 Next iteration the condition a < 3 fails as a = 4 Therefore it comes out of the loop and prints the value of b which is 5. I hope this was of some help!
16th May 2020, 6:21 AM
Riya Savant
Riya Savant - avatar
0
Thank You :) i got it
16th May 2020, 6:58 AM
Mateusz Legend
Mateusz Legend - avatar