455,844 Members | 1,413 Online
Need help? Post your question and get tips & solutions from a community of 455,844 IT Pros & Developers. It's quick & easy.

Newbie trying to understand nested loops

 P: 2 I am trying to understand the following code: Expand|Select|Wrap|Line Numbers  my @arr1=(5,3,2,1,4);  my \$i=0;  my \$j=0;  \$tmpnum  for(\$i=0;\$i<@arr1;\$i++) {   for(\$j=0;\$j<@arr1;\$j++)   {    if(\$arr1[\$i]<\$arr1[\$j])       {      \$tmpnum=\$arr1[\$i];     \$arr1[\$i]=\$arr1[\$j]   \$arr1[\$j]=\$tmpnum;   };  };  };      foreach(@arr1) {   print \$_ . "\n"; } When I look at the first for loop I know that @arr is 5 (which represents the total number of indexes). So then the condition is met because 0 is less than 5. I am then assuming that the Perl moves onto the second loop and the condition is met also and Perl then moves onto the if statement. Now here is where I get confused. If this were the first run of the script the condition in the if statement would not be meet because 5 is not less than 5 (\$i and \$j would both be 5 because they would be both zero and zero represents the first index which is 5. So if that is the case does the script exit the second loop and go back to the first one and increment by 1 or does it go back to the second loop and increment by 1? I believe I was told that it goes to the second loop so \$j which was 0 would increment to 1. If that is the case the if statement would the read as if(\$arr1[5]<\$arr1[3] (5 and 3 representing the index based on the variable) and that does not make any sense to me especially since J would keep on incrementing and \$j would never be greater than \$i. If I go back to the first loop that does not make any sense to me either because \$i would increment by 1 and then I would have to move onto the next loop and \$j would increment by 1 and when I get to the if condition I am stuck because 3 would not be less than 3 (3 representing the second index of the array). What am I missing here? Apr 12 '08 #1