Laurent_R
Veteran
/ Moderator
Dec 28, 2013, 9:18 AM
Post #3 of 4
(1536 views)

Re: [ToeKnuckle] for loop problem
[In reply to]

Can't Post


OK, the addition of the last statement prevents your program from looping forever, but I doubt that's really what you want. Output of your program:
1 times 1 equals 1 2 times 1 equals 2 3 times 1 equals 3 4 times 1 equals 4 5 times 1 equals 5 That's not really the multiplication tables that you presumably want to print out (otherwise I don't see the point of nested loops). The error in your program lies in this line:
for (my $k = 1; $i < 6;$k++) The condition to stop the loop is on $i instead of being on $k. Remove the last statement, and change $i to $k in your inner loop statement, this changes your program to this:
for (my $i = 1;$i < 6;$i++) { for (my $k = 1; $k < 6;$k++) { print "$i times $k equals " . $i * $k . "\n"; } } Now the output is probably what you are looking for:
1 times 1 equals 1 1 times 2 equals 2 1 times 3 equals 3 1 times 4 equals 4 1 times 5 equals 5 2 times 1 equals 2 2 times 2 equals 4 2 times 3 equals 6 2 times 4 equals 8 2 times 5 equals 10 3 times 1 equals 3 3 times 2 equals 6 3 times 3 equals 9 3 times 4 equals 12 3 times 5 equals 15 4 times 1 equals 4 4 times 2 equals 8 4 times 3 equals 12 4 times 4 equals 16 4 times 5 equals 20 5 times 1 equals 5 5 times 2 equals 10 5 times 3 equals 15 5 times 4 equals 20 5 times 5 equals 25 Having said that, Perl has much better looping constructs than C and can do what you want in much less typing:
for my $i (1..5) { print "$i times $_ equals " . $i * $_ . "\n" for (1..5); } Which produces the following output:
$ perl multipl.pl 1 times 1 equals 1 1 times 2 equals 2 1 times 3 equals 3 1 times 4 equals 4 1 times 5 equals 5 2 times 1 equals 2 2 times 2 equals 4 2 times 3 equals 6 2 times 4 equals 8 2 times 5 equals 10 3 times 1 equals 3 3 times 2 equals 6 3 times 3 equals 9 3 times 4 equals 12 3 times 5 equals 15 4 times 1 equals 4 4 times 2 equals 8 4 times 3 equals 12 4 times 4 equals 16 4 times 5 equals 20 5 times 1 equals 5 5 times 2 equals 10 5 times 3 equals 15 5 times 4 equals 20 5 times 5 equals 25
