4

Write PLSQL block to display the ODD numbers and total odd numbers in given number? Ex: If given number is 3, display as below 1 is odd number 3 is odd number Total 2 odd numbers in 3

CREATE OR REPLACE PROCEDURE odd_num(p_num NUMBER ) 
   IS s_num NUMBER;
BEGIN 
   FOR i_num IN 1..p_num  
      LOOP   
         IF mod(i_num,2) = 1 
         THEN     
            dbms_output.put_line(i_num ||' is Odd Number');  
         END IF; 
      END LOOP;  
   dbms_output.put_line('Total '|| s_num ||' Odd Numbers in '||p_num);
END;
1
  • What is the question? It appears that you'd want to initialize s_num and then increment it in the if statement in your loop. Commented Jun 17, 2015 at 5:29

1 Answer 1

8

You just need to initialize and assign the counter to s_num. Just add the following inside the IF block:

s_num := s_num +1;

For example,

SQL> CREATE OR REPLACE PROCEDURE odd_num(p_num NUMBER )
  2  IS
  3  s_num NUMBER;
  4  BEGIN
  5     s_num :=0;
  6     FOR i_num IN 1..p_num
  7        LOOP
  8           IF mod(i_num,2) = 1
  9           THEN
 10              -- Increment the counter once for each iteration
 11              s_num := s_num +1;
 12              dbms_output.put_line(i_num ||' is Odd Number');
 13           END IF;
 14        END LOOP;
 15     dbms_output.put_line('Total '|| s_num ||' Odd Numbers in '||p_num);
 16  END;
 17  /

Procedure created.

SQL> sho err
No errors.

Let's execute the procedure:

SQL> SET SERVEROUTPUT ON
SQL> EXEC odd_num(5);
1 is Odd Number
3 is Odd Number
5 is Odd Number
Total 3 Odd Numbers in 5

PL/SQL procedure successfully completed.

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

2 Comments

I want the answer like "Total 3 odd numbers in 5".
@PrabhaChrist Welcome to Stack Overflow. I know, I updated. There was a silly typo, I added the counter inside the loop before IF, it should be inside IF block. Please mark it answered.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.