3-12. Stepping Through a Loop Based on Odd-Numbered Increments

Problem

Rather than iterating through a range of numbers by even increments, you prefer to loop through the range using odd increments.

Solution

Use the built-in MOD function to determine whether the current index is odd. If it is odd, then print out the value; otherwise, continue to the next iteration. The following example shows how to implement this solution:

BEGIN
  FOR idx IN 1..10 LOOP
    IF MOD(idx,2) != 0 THEN
      DBMS_OUTPUT.PUT_LINE('The current index is: ' || idx);
    END IF;
  END LOOP;
END;

Results:

The current index is: 1
The current index is: 3
The current index is: 5
The current index is: 7
The current index is: 9

PL/SQL procedure successfully completed.

How It Works

The solution depicts one possible workaround for a STEP replacement. Using the MOD function to determine whether a number is odd works quite well. The MOD function, otherwise known as the modulus function, is used to return the remainder from the division of the two numbers that are passed into the function. Therefore, this function is useful for determining even or odd numbers. In this case, if any value is returned from MOD, then the number is assumed to be odd, and the statements within the IF statement will be executed.

Such a technique may be useful in the case of iterating through a collection of data such as a table. If you want to grab every other record from the collection, then performing a stepping solution such as this or the solution from Recipe 3-11 will allow you to achieve the desired result. You could easily use the resulting index from this technique as the index for a collection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.31.50