0

1 - Explain the working of this code?

#include <iostream> using namespace std; int main() { int x = 5, y = 3; while(x) { y += x; x--; } cout << y; return 0; } Output : 18

18th Jan 2019, 8:01 AM
Sm Developer
Sm Developer - avatar
2 Answers
+ 2
with each iteration of the while loop, the variable x is added to the variable y (y+=x), then the variable x decreases by 1 (x--), the loop will stop when x = 0. we get: y = 3 + 5 + 4 + 3 + 2 + 1 = 18
18th Jan 2019, 8:34 AM
Игорь Яковенко
Игорь Яковенко - avatar
+ 2
OK I understand it Now thanks
18th Jan 2019, 12:06 PM
Sm Developer
Sm Developer - avatar