|
-
Jan 26th, 2013, 09:49 AM
#1
Thread Starter
Addicted Member
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.
-
Jan 26th, 2013, 07:04 PM
#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.
-
Jan 26th, 2013, 08:07 PM
#3
Thread Starter
Addicted Member
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
-
Jan 27th, 2013, 11:13 AM
#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:
So your code becomes
Code:
<?php
$i = 1;
while($i <=5){
echo "The square root of " .$i." is " .$i*$i ."<br/>";
$i++;
}
?>
-
Feb 1st, 2013, 06:39 PM
#5
Thread Starter
Addicted Member
Re: Why an extra number with WHILE function results?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|