Home > Back-end >  Numbers that are divisible by 2 and 3 are not printing in PL/SQL
Numbers that are divisible by 2 and 3 are not printing in PL/SQL

Time:10-26

First 20 numbers that are divisible by both 2 and 3 are not printing. Instead, bunch of 0's show up.

I am trying to print first 20 numbers that are divisible by both 2 and 3. Below is my code:

SET SERVEROUTPUT ON;

DECLARE 
    n number := 0;
    
BEGIN
    WHILE n <= 40
    LOOP
        IF MOD (n, 6) = 0 THEN
        DBMS_OUTPUT.PUT_LINE(n);
        END IF;
    END LOOP;
END;

The output is giving me bunch of 0's. Any ideas as to what I can change to make it work?

CodePudding user response:

You are never incrementing n.

And also, there are not 20 numbers divisible by 6 in the range [0 .. 40]. Instead count the number of results

SET SERVEROUTPUT ON;

DECLARE 
    n number := 0;
    c number := 0;
    
BEGIN
    WHILE c < 20
    LOOP
        IF MOD (n, 6) = 0 THEN
            DBMS_OUTPUT.PUT_LINE(n);
            c := c   1;
        END IF;
        n := n   1;
    END LOOP;
END;
  • Related