Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Need help with nested for loops

by blindluke (Hermit)
on Jan 07, 2015 at 20:11 UTC ( [id://1112559]=note: print w/replies, xml ) Need Help??


in reply to Need help with nested for loops

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1112559]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2025-12-12 15:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (92 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.