You are probably expecting consecutive index numbers, but you are printing the results of the  $i * $g multiplication. During the first outer loop iteration,  $i = 1, $g = 1 .. 20, you will get what you expect. During the second,  $i = 2, and multiplying it by the range 1 .. 20 results in 2, 4, 6, 8, ... instead of the 21, 22, 23 ... range you probably want.

In simple assignments like this one, it's good to test your loop on paper, until you are sure the method works.

Also, take a look at the range operator. You can write your loops in a much more readable way:

for my $i (1..6) { print "$i\n"; }

Update:

Take a look at the following example. It's not your exactly your homework assignment, but upon closer inspection you will find that it solves the same problem. Notice the range operator, the modulo operator, and think on why the $grp = 5 if $grp == 0; is needed. Modify the code to suit your needs, and good luck with your next assignments.

#!/usr/bin/perl use warnings; use strict; for my $id (1 .. 30) { my $grp = $id % 5; $grp = 5 if $grp == 0; printf ("ID: %03d\t GRP: %d \n", $id, $grp); }

- Luke


In reply to Re: Need help with nested for loops by blindluke
in thread Need help with nested for loops by fidda

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.