473,473 Members | 2,003 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Newbie trying to understand nested loops

2 New Member
I am trying to understand the following code:

Expand|Select|Wrap|Line Numbers
  1.  my @arr1=(5,3,2,1,4);
  2.  my $i=0;
  3.  my $j=0;
  4.  $tmpnum
  5.  for($i=0;$i<@arr1;$i++) {
  6.   for($j=0;$j<@arr1;$j++)   {
  7.    if($arr1[$i]<$arr1[$j])       {
  8.      $tmpnum=$arr1[$i];
  9.     $arr1[$i]=$arr1[$j]
  10.   $arr1[$j]=$tmpnum;
  11.   };
  12.  }; 
  13. };
  14.  
  15.  
  16.  foreach(@arr1) {
  17.   print $_ . "\n";
  18. }
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
3 1370
Ganon11
3,652 Recognized Expert Specialist
Your interpretation of the first run through the first loop is correct, but only because your first element is the largest. It might help if you have some proper indenting of your code:

Expand|Select|Wrap|Line Numbers
  1. my @arr1=(5,3,2,1,4);
  2. my $i=0;
  3. my $j=0;
  4. $tmpnum # should be my $tmpnum;
  5. for($i=0;$i<@arr1;$i++) {
  6.     for($j=0;$j<@arr1;$j++) {
  7.         if($arr1[$i]<$arr1[$j]) {
  8.             $tmpnum=$arr1[$i];
  9.             $arr1[$i]=$arr1[$j]
  10.             $arr1[$j]=$tmpnum;
  11.         };
  12.     };
  13. };
  14.  
  15. foreach(@arr1) {
  16.     print $_ . "\n";
  17. }
Ahh, much better and easier to read! Now, about those loops:

We enter loop 1: $i is 0.
We enter loop 2: $j is 0.
Is $arr1[$i] < $arr1[$j]? Well, $i = 0, $j = 0, $arr1[0] = 5, and 5 is not less than 5. So the if statement is not executed. We skip past the if statement.
Exit loop 2. We increment $j to 1.
Is $j < @arr1? $j = 1, @arr1 = 5, 1 < 5, so the loop goes again. Enter loop 2.
Is $arr1[$i] < $arr1[$j]? Well, $i = 0, $j = 1, $arr1[0] = 5, $arr[1] = 3, and 5 is not less than 5. So the if statement is not executed. We skip past the if statement.

(blah blah blah, until...)
We increment $j to 5.
Is $j < @arr1? $j = 5, @arr1 = 5, and 5 is not less than 5, so we no longer execute loop 2.
Exit loop 1. Increment $i to 1. Check: is $1 < @arr1? Yes, because 1 < 5. Enter loop 1.
Enter loop 2: $j = 0 again! Not 1!
Is $arr1[$i] < $arr1[$j]? Well, $i = 1, $j = 0, $arr1[1] = 3, $arr1[0] = 5, and 3 < 5! So the if statement executes!
The if statement swaps the two values, making @arr1 contain (3,5,2,1,4).
Exit loop 2. We increment $j to 1.

(blah blah blah)

Hopefully that explains the nested loops in this circumstance a little better.
Apr 12 '08 #2
KevinADC
4,059 Recognized Expert Specialist
The code has a couple of syntax errors but assuming those are fixed, the code is doing a basic bubble sort. Does the same as:

Expand|Select|Wrap|Line Numbers
  1. @arr1 = sort {$a <=> $b} @arr1;
Apr 12 '08 #3
eWish
971 Recognized Expert Contributor
Kevin's example it much easier to understand. That is the way I would go.

--Kevin
Apr 12 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

25
by: chad | last post by:
I am writing a program to do some reliability calculations that require several nested for-loops. However, I believe that as the models become more complex, the number of required for-loops will...
0
by: Xah Lee | last post by:
# -*- coding: utf-8 -*- # Python # David Eppstein of the Geometry Junkyard fame gave this elegant # version for returing all possible pairs from a range of n numbers. def combo2(n): return...
4
by: dw | last post by:
Hello all. We're doing a site with teams and their members. We've got a page where we need to display people according to who belongs to a which team. I've heard that nested loops are bad, but...
46
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are...
8
by: Mike Wertheim | last post by:
Hi, I'm using PostgreSQL 8. I have two tables that I am doing a join on, and the join executes very slowly. The table called Notification has a text field called NotificationID, which is...
77
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop....
9
by: Gregory Petrosyan | last post by:
I often make helper functions nested, like this: def f(): def helper(): ... ... is it a good practice or not? What about performance of such constructs?
33
by: Adam Chapman | last post by:
Hi, Im trying to migrate from programming in Matlab over to C. Im trying to make a simple function to multiply one matrix by the other. I've realised that C can't determine the size of a 2d...
8
by: Nathan Sokalski | last post by:
I have several nested For loops, as follows: For a As Integer = 0 To 255 For b As Integer = 0 To 255 For c As Integer = 0 To 255 If <Boolean ExpressionThen <My CodeElse Exit For Next If Not...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.