SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    May 2010
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question 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. #2
    SitePoint Zealot
    Join Date
    Nov 2009
    Posts
    110
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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. #3
    SitePoint Member
    Join Date
    May 2010
    Posts
    12
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much. I got it.


Bookmarks

Posting Permissions

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