CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
While loop

 



intperl
New User

Aug 3, 2014, 11:01 PM

Post #1 of 5 (2543 views)
While loop Can't Post

Hi,

$i=0;
while($i<=10){
print "$i\n";
$i++;
}

It prints 0 to 10 correctly but

$i=0;
while($i<=10){
$i++;
print "$i\n";
}
it prints 1 to 11, I dont know Y it prints till 11 , when it cheks 11 it should come out of loop without printing it right why it s printing 11?


Laurent_R
Veteran / Moderator

Aug 3, 2014, 11:16 PM

Post #2 of 5 (2541 views)
Re: [muthu] While loop [In reply to] Can't Post

This is perfectly normal. In your second example, when $i reaches 10, it still goes once through the while loop (because, at this point, $i <= 10 is still true.) Then $i is incremented, going to 11 and is printed. It is only then that, going to the while once more that the loop is interrupted because, by now, $i <= 10 is no longer true).

In other words, your result has to do with the order in which the operations are done: first check if $i is <= 10, then increment $i and print it.


intperl
New User

Aug 3, 2014, 11:33 PM

Post #3 of 5 (2539 views)
Re: [Laurent_R] While loop [In reply to] Can't Post

ok anyway when it incremented $i++ to 11 it will go to check the condition, then it should exit right without printing 11?

my understanding is

0 condition 0 <= 10 true
print "0";
$i++ ;
1 condition 1<=10 true
print "1";
$i++;
2 condition 2<=10 true
print "2";
$i++
.
.
.
9 condition 9<=10 true
print "9";
$i++
10 condition 10<=10 true
print "10";
$i++ #11
11 condition 11<=10 false
It should not print right

$i=0;
while($i<=10){
$i++;
print "$i\n";
}

In Reply To


Laurent_R
Veteran / Moderator

Aug 4, 2014, 9:58 AM

Post #4 of 5 (2519 views)
Re: [intperl] While loop [In reply to] Can't Post

No.

When you have such a loop:

Code
$i=0; 
while($i<=10){
$i++;
print "$i\n";
}


the program executes the code lines in the order they are written:
- while ... -> checks value of $i
- $i++ ; -> increments $i (it is by now too late to check if the value is larger than 10, it will happen only the next time the while ... line is reached)
- print "$i\n"; prints $i
- and now only back to the while than checks the value, and now only will exit the loop id the while condition is not met.

This is the way it works in all programming languages that I know about (i.e. dozens of them).


intperl
New User

Aug 4, 2014, 11:46 PM

Post #5 of 5 (2486 views)
Re: [Laurent_R] While loop [In reply to] Can't Post

Thanks Laurent.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives