## Forum Stats

• 3,767,857 Users
• 2,252,726 Discussions

Discussions

# Printing Numbers in order

I have a record type defined and assigned values from 1 to 5. If we give input as 4 then the output should be 45123. and if we give input as 3 then the output should be 34512.

we are using two for loops to achieve this. How can we do it on a single loop?

declare

type a is record(a1 number);

type b is table of a;

arr b := b();

n number :=4;

begin

arr.extend(5);

arr(1).a1 := 1;

arr(2).a1 := 2;

arr(3).a1 := 3;

arr(4).a1 := 4;

arr(5).a1 := 5;

for i in n..arr.count loop

dbms_output.put_line(arr(i).a1);

End Loop;

for i in 1..n-1 loop

dbms_output.put_line(arr(i).a1);

End Loop;

end;

Tagged:

• Replace the two loops with the following single loop:

``` for i in 1..arr.count loop
dbms_output.put_line(arr(1 + mod(n + i - 2, arr.count)).a1);
End Loop;
```

For i = 1 the array index is 1 + mod(n-1, arr_count) which, as long as n is between 1 and arr.count, will equal n. Then as i increases, the array index increases by increments of 1, until n + i - 2 = arr.count, at which point mod(n + i - 2, arr.count) is 0 and the array index is 1. Then the array index continues to grow by increments of 1 until all the numbers are printed.

``` for i in 1..arr.count loop