Why an extra number with WHILE function results?-VBForums

# Thread: Why an extra number with WHILE function results?

1. ## Why an extra number with WHILE function results?

Hello Folks,

I used a piece of code to test the square root of some numbers in a JAVA application using 'DO' 'WHILE' functions and everything worked well. So, I decided to do the same thing using PHP. I have tried both the 'WHILE' and 'DO WHILE' functions in PHP. They both work fine except that I get an extra number. Could someone have a look at my code and see what I am doing wrong, please?

Code:
<?php
\$i = 1;

while(\$i <=5){
echo "The square root of " .\$i." is " .\$i*\$i ."<br/>";
\$i++;
}
echo \$i;
?>
When I run the code above, I get the output below.
Code:
The square root of 1 is 1
The square root of 2 is 4
The square root of 3 is 9
The square root of 4 is 16
The square root of 5 is 25
6
Why do I get 6 which is an extra number added to it?

Any help will be much appreciated.

2. ## Re: Why an extra number with WHILE function results?

Because that is what you told the program to do.

You go through your while loop incrementing \$i every iteration. When \$i = 6, then your while condition is false and it exits the loop. Once you exit the loop, you've echoed \$i again which, at this point, is now 6.

3. ## Re: Why an extra number with WHILE function results?

Hi,

Thanks for your response to my message. I got your explanations. But how do I get around this problem now? Any solution, please?

Thanks,
Menre

4. ## Re: Why an extra number with WHILE function results?

If you understood the explanation, you should have been able to fix the problem...

To fix it, remove this line:

Code:
echo \$i;

Code:
<?php
\$i = 1;

while(\$i <=5){
echo "The square root of " .\$i." is " .\$i*\$i ."<br/>";
\$i++;
}
?>

5. ## Re: Why an extra number with WHILE function results?

Thanks a lot.
Menre

#### Posting Permissions

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

Featured