Why output of this code is 6? It is supposed to be 5 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why output of this code is 6? It is supposed to be 5

https://code.sololearn.com/wwZcqzjG76nI/?ref=app

18th Jul 2019, 1:27 PM
Денис Лапшин
Денис  Лапшин - avatar
5 Answers
+ 12
Its because after the sum will be greater than 10 the value of variable i at that time will be 5 and then the i will get incremented by 1, so it's value will become 6. Then the condition is checked and it is evaluated to be false. So the final value of variable i will be 6. You can check the code for more understanding : https://code.sololearn.com/wG24Qaz3hO05/#php Hope this helps !!!
18th Jul 2019, 1:56 PM
Nova
Nova - avatar
+ 10
Денис Лапшин First initialization is done once. Then the condition is checked, then the set of code inside for loop is executed and then the value of variable in updated. You can get the proper explanation from the below website : https://www.elated.com/php-for-loops/
18th Jul 2019, 3:53 PM
Nova
Nova - avatar
+ 2
It's because you're starting $i at 1. Here's the loop step-by-step: $sum = 0; $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for ($i = 1, $a = 0; $sum <= 10; $i++, $a++) LOOP 1: $sum += $arr[0] = 0+1 = 1, $i + 1 = 2 LOOP 2: $sum += $arr[1] = 1+2 = 3, $i + 1 = 3 LOOP 3: $sum += $arr[2] = 3+3 = 6, $i + 1 = 4 LOOP 4: $sum += $arr[3] = 6+4 = 10, $i + 1 = 5 LOOP 5: $sum += $arr[4] = 10+5 = 15, $i + 1 = 6 - conditions satisfied Change i$i to 0 and it should work.
18th Jul 2019, 1:46 PM
Rincewind
Rincewind - avatar
+ 2
Thanks Keval. I thought firstly condition should be checked and then incremented/decremented or something else.
18th Jul 2019, 3:45 PM
Денис Лапшин
Денис  Лапшин - avatar
+ 1
Thanks a lot, Keval
18th Jul 2019, 4:43 PM
Денис Лапшин
Денис  Лапшин - avatar