# Thread: A simple code I dont understand

1. ## A simple code I dont understand

<?php
\$i=0;
\$s=0;
while (\$i<=7){
\$i=\$i+1;
\$s+=\$i;
}
print \$s;
?>

WHy the answer is 36 while I think 28 should be the right one?

<?php
\$i=0;
\$s=0;
while (\$i<=100){
\$i=\$i+1;
\$s+=\$i;
}
print \$s;
?>
WHy the answer is 5151 while I think 5050 should be the right one?

Thank you 。

2. Hi there,

i saw your post and i thought i would have a stab at it. I wrote u'r code and worked it out on paper, here is what i got:

\$i = 1; // when condition is 0
\$s = 1;

\$i = 2; // when condition is 1
\$s = 3;

\$i = 3; // when condition is 2
\$s = 6;

\$i = 4; // when condition is 3
\$s = 10;

\$i = 5; // when condition is 4
\$s = 15;

\$i = 6; // when condition is 5
\$s = 21;

\$i = 7; // when condition is 6
\$s = 28;

\$i = 8; // when condition is 7
\$s = 36;

In the condition you have <=7, so when \$i = 7, it will go through the loop 1 more time because it satisfies the requirement which is why it outputs \$36. When yo have a loop like u'rs, try to write it on paper rather than thinking about it, it is human error to get it wrong like that but writing it on paper means you understand how the loop is working. Hope that helps you.

It should also answer u'r second loop question.

3. Thank you very much. I got it.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•