On 7/8/11 Fri Jul 8, 2011 4:33 PM, "J. S. John" <phillyj...@gmail.com> scribbled:
> Hi all, > I'm teaching myself perl. Right now, I am stuck with this script. I > don't understand how it works. I know what it does and how to do it by > hand. > > $n = 1; > while ($n < 10) { > $sum += $n; > $n += 2; > } > print "The sum is $sum.\n" > > I know $sum is initially 0 (undef). I see that $sum becomes 1, then $n > becomes 3. The loop goes back and then I don't understand. Now $sum is > 1+3? Yes. The while loop will repeat as long as its conditional expression is true. In this case, it will loop as long as $n is less than 10. Since $n is 1 at the beginning of the loop and incremented by 2 during each iteration of the loop, $n will have the successive values 1, 3, 5, 7, and 9 during 5 loop iterations. At the beginning of the 6th iteration, $n has the value 11. Since the logical expression '$n < 10' is now false, the loop body is skipped, and execution resumes at the first line after the loop body (the print statement). At the end of the loop, $sum should have the value 1 + 3 + 5 + 7 + 9, or 25. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/