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

2015/5/18

what is the value of sum after the following code is executed?

ipeefreely ipeefreely

2015/5/18

#
sum = 0; 
for (x = 2; x < 6; x = x + 1)
{
sum = sum + x;
}
danpost danpost

2015/5/18

#
The code will not compile as 'sum' and 'x' are not declared anywhere. However, if you had this:
int sum = 0;
for (int x=2; x<6; x=x+1)
{
    sum = sum+x;
}
then sum = 0+2, +3, +4, +5 = 14. I believe that this would work also:
int sum = 0;
for (int x=2; x<6; x++, sum+=x);
In fact, this may even work:
int sum = 0;
for (int x=2; x<6; sum+=(++x));
You need to login to post a reply.