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;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With