This discussion is archived
3 Replies Latest reply: Apr 4, 2013 12:04 PM by chris227

nested loops

Currently Being Moderated
db 10g rel2 , hi all,
i am trying to understand the way the process of nested loops is run :
i am writing this nested
`````` begin
for i in 1..2 loop
dbms_output.put_line('df') ;
for i in 1..2 loop
dbms_output.put_line('ss') ;
end loop ;
end loop ;
end ;``````
and i get a result rather than which i expect , i get this result :
``````df
ss
ss
df
ss
ss``````
while i was expecting
``````df
ss
df
ss``````
so i think i understand it wrong , if you could clarify it to me please .
• 1. Re: nested loops
Currently Being Moderated
The inner loop is processed in total in every loop of the outer loop.
This means in the first loop of the outer loop the inner loop processes 2 loops
and in the second also. That's 4 in sum.
For your expected result you just need one loop
``````for i in 1..2 loop
dbms_output.put_line('df') ;
dbms_output.put_line('ss') ;
end loop ;``````
• 2. Re: nested loops
Currently Being Moderated
``````begin
for i in 1..2 loop  -- loop 1 - outer loop
dbms_output.put_line('df') ;
for i in 1..2 loop  -- loop 2 - inner loop
dbms_output.put_line('ss') ;
end loop ;
end loop ;
end ;``````
This line
`` for i in 1..2 loop  -- loop 1 - outer loop``
says: do everything in this loop two times

And one of the things in loop 1 is this
`` for i in 1..2 loop  -- loop 2 - inner loop``
Which says: when you get here do everything in this loop two times

So how is it that you expect this
`````` for i in 1..2 loop  -- loop 2 - inner loop
dbms_output.put_line('ss') ;
end loop ;``````
To only produce 'ss' one time?
• 3. Re: nested loops
Currently Being Moderated
Hi,

Let's number the lines, to make it easier to talk about it:
``````begin                         -- Line 1
for i in 1..2 loop               --      2
dbms_output.put_line('df');     --     3
for i in 1..2 loop          --     4
dbms_output.put_line('ss');     --     5
end loop ;               --     6
end loop ;                     --     7
end ;                              -- Line 8``````
You can think of the order in which the lines get executed as:

2 (outer i = 1)
3 ('df' printed)
4 (inner i = 1)
5 ('ss' printed)
6
4 (inner i = 2)
5 ('ss' printed)
6
7
2 (outer i = 2)
3 ('df' printed)
4 (inner i = 1)
5 ('ss' printed)
6
4 (inner i = 2)
5 ('ss' printed)
6
7

The inner loop is run as often as required before the outer loop increments.

What order were you expecting?

By the way, it's confusing to use use the same variable name for two (or more) different variables in the same piece of code. If you're using i for the index variable of the outer loop. then use something different, such as j, for the index variable of the inner loop.

Legend

• Correct Answers - 10 points