Forum Stats

  • 3,767,857 Users
  • 2,252,726 Discussions
  • 7,874,365 Comments

Discussions

Printing Numbers in order

Dharani123
Dharani123 Member Posts: 71 Blue Ribbon
edited Mar 9, 2021 5:36AM in SQL & PL/SQL

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:

Best Answer

  • mathguy
    mathguy Member Posts: 10,144 Blue Diamond
    Accepted Answer

    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.

    Dharani123

Answers

  • mathguy
    mathguy Member Posts: 10,144 Blue Diamond
    Accepted Answer

    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.

    Dharani123