0

Can someone explain in detail why I run the following code and it gives me 👉15👈??

//here's the KOTLIN code: fun main(args: Array<String>) { var sum = 3 var i = 3 while (i<=5) { sum += i i++ } println(sum) } // I would be thrilled if anyone care to explain step by step as how this code runs 🙏🙏

16th Sep 2022, 3:27 PM
Rerenga Ioane
Rerenga Ioane - avatar
5 ответов
+ 3
Which result did you expect and why? :) The code calculates 3+3+4+5 which yields 15.
16th Sep 2022, 3:52 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 3
Certainly. I was only hoping that you'd give me some insight into your thinking, so that i can pinpoint the problem :). If you look at the while loop, you see that it runs until i is 6. That is the terminating condition (runs while i<=5, or stops a soon as i>5, which in this case is i==6). That means that the loop body, the part between the curly braces, is executed for the values 3, 4, and 5 of i - because i was initialially set to 3. What the loop body does (besides incrementing i) is add these values of i to 'sum'. Thus you get 'sum+3' in the first cycle, 'sum+3+4' in the second cycle, and lastly 'sum+3+4+5' in the last. After that, i becomes 6 which is larger than 5 and the loop ends. All that only makes sense if 'sum' has some initial value. The loop only modifies the current value of 'sum'. And if you look at the beginning you'll see that sum was initialized to 3. Thus, after the loop terminates, sum has its initial value pls the values it received in the loop. And that sums up to 3+3+4+5
17th Sep 2022, 5:40 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
Your explaination has been of tremendous help, my friend. You're the best 🙏🙏👍 Thanks to you, I shall now continue my lessons on KOTLIN. Sorry again for taking much of your time.
17th Sep 2022, 3:58 PM
Rerenga Ioane
Rerenga Ioane - avatar
+ 1
No problem :)
17th Sep 2022, 4:18 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
0
Dear Ani, would you care to comment further on how you got the 3, 3, 4 and 5? I would really want to understand it sir/mam 🙏♥️
16th Sep 2022, 7:57 PM
Rerenga Ioane
Rerenga Ioane - avatar