Home: Perl Programming Help: Intermediate:
While loop

intperl
New User

Aug 3, 2014, 11:01 PM

Views: 5297
 While loop
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

Views: 5295
 Re: [muthu] While loop
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

Views: 5293
 Re: [Laurent_R] While loop
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";
}

Laurent_R
Veteran / Moderator

Aug 4, 2014, 9:58 AM

Views: 5273
 Re: [intperl] While loop
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

Views: 5240
 Re: [Laurent_R] While loop
Thanks Laurent.