1

I want some PL/SQL code which prints 1 to 100. Additionally for numbers divisible by 3 print 'wel', for numbers divisible by 5 print 'come' and for numbers divisible by 3 and 5 then print 'welcome'. Output like this

    1
    2
    wel
    4
    come
    7
    .
    .
    14
   welcome

Here is some code I have written:

begin
    for i in 1..100 loop
        dbms_output.put_line(i);
       if  mod(i,3)=0 then
            dbms_output.put_line('wel');
        elsif mod(i,5)=0 then
            dbms_output.put_line('come');
        elsif mod(i,3)=0 and mod(i,5)=0 then
            dbms_output.put_line('welcome');
        end if;
    end loop;
end;
/
1
  • 2
    The problem with the code you have posted is that it lists the condition test in the wrong order. A value of 15 is both divisible by 3 and by 5: so it you want to do something specific for multiples of 15 you need to test for divisible by 15 before testing for either divisible by 3 or divisible by 5. More generally, put start switch evaluations (case, if ... elsif..) with the most specific condition and progress towards the most general (the most general of all of course being else). Commented Jul 13, 2018 at 14:03

1 Answer 1

4

It looks like variation of Fizzbuzz interview question. You could use single query:

SELECT nvl(decode(mod(rownum,3),0,'wel')||decode(mod(rownum,5),0,'come'),rownum)
       as Example
FROM xmltable('1 to 100');

DBFiddle Demo

EDIT

PL/SQL block:

BEGIN
  FOR i IN (
  SELECT nvl(decode(mod(rownum,3),0,'wel')||decode(mod(rownum,5),0,'come'),rownum)
       as Example
  FROM xmltable('1 to 100')) LOOP
      DBMS_OUTPUT.PUT_LINE(i.Example);
  END LOOP;
END;

DBFiddle Demo2

EDIT 2

As you posted your code is is very easy to fix it:

begin
for i in 1..100 loop
  if mod(i,3)=0 and mod(i,5)=0 then
    dbms_output.put_line('welcome');
  elsif mod(i,5)=0 then
    dbms_output.put_line('come');
  elsif mod(i,3)=0 then
    dbms_output.put_line('wel');
  else 
   dbms_output.put_line(i);
  end if;
end loop;
end;
//

DBFiddle Demo3

Sign up to request clarification or add additional context in comments.

4 Comments

Please read I want a Ans in PLSQL And printing a Number 1 to 100 In For Loop Then I want to use If, elsif statements
@lukasz_szozda Thank you sir, But I need explanation why u change that order ??
I will take some credit for this: dba.meta.stackexchange.com/a/3000 cheers!
@KaushikNayak That's really great :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.