oracle-databaseplsql

PL SQL output in hackerrank


set serveroutput on;
DECLARE
I NUMBER;
J NUMBER;
BEGIN
FOR I IN REVERSE 1..20
LOOP
    FOR J IN 1..I
    LOOP
    DBMS_OUTPUT.PUT('* ') ; -- printing *
    END LOOP;
    DBMS_OUTPUT.NEW_LINE; -- for new line
END LOOP;
END;

'

Can anyone tell me why this code is not showing any output in the Hackerank question (Draw The Triangle) even after selecting Oracle?

https://www.hackerrank.com/challenges/draw-the-triangle-1/problem


Solution

  • That site doesn't seem to ever show your the output from your submission, unhelpfully, but does with just 'run code'. Surprisingly it does seem to understand PL/SQL; and even more surprisingly it handles the set serveroutput on, which is a SQL\Plus/SQL Developer client command.

    But you need to add a terminating / after your code, on a line on its own - again, just like SQL*Plus (though SQL Developer is sometimes doesn't complain):

    END LOOP;
    END;
    /
    

    Your code doesn't produce the expected output because it has a trailing space on each line. Instead of:

        DBMS_OUTPUT.PUT('* ') ; -- printing *
    

    skip the space on the last iteration:

        DBMS_OUTPUT.PUT('*') ; -- printing *
        IF J < I THEN
            DBMS_OUTPUT.PUT(' ');
        END IF;
    

    So this produces the expected output, and passes the test:

    set serveroutput on;
    DECLARE
    I NUMBER; -- redundant
    J NUMBER; -- redundant
    BEGIN
    FOR I IN REVERSE 1..20
    LOOP
        FOR J IN 1..I
        LOOP
        DBMS_OUTPUT.PUT('*') ; -- printing *
        IF J < I THEN
            DBMS_OUTPUT.PUT(' ');
        END IF;
        END LOOP;
        DBMS_OUTPUT.NEW_LINE; -- for new line
    END LOOP;
    END;
    /
    

    Screenshot from HackerRank

    However, your original code also passes the test, despite the trailing spaces, if you just add the terminating /:

    enter image description here