This site requires JavaScript, please enable it in your browser!
Greenfoot back
aromero2
aromero2 wrote ...

2015/7/24

Please help

aromero2 aromero2

2015/7/24

#
I twice recently missed the following type of question in a test and I'm having trouble understanding How is the answer 14? Could someone explain it to me, please? What is the value of sum after the following is executed? sum = 0; for ( x = 2; x < 6 ; x = x + 1 ) { sum = sum + x; }
gulzaibthegreat1 gulzaibthegreat1

2015/7/24

#
okay so your doing a for loop, this means that the piece of code within the brackets (sum = sum + x) keeps occuring under the following condition, x < 6. Each time the code occurs x increases by 1. From here we can get to the math, x starts at 2, sum = sum (0 at start) + 2 = 2. Then x = 2 + 1 = 3 sum (2) + 3 = 5 x = 3 + 1 = 4 sum (5) + 4 = 9 x = 4 + 1 = 5 sum (9) + 5 = 14 x = 5 + 1 = 6 X IS NO LONGER LESS THAN 6 SO THE CODE STOPS. Your final sum is 14. 2 + 3 + 4 + 5 = 14
aromero2 aromero2

2015/7/26

#
Thanks so much this really helped me grasp it!
You need to login to post a reply.