1. Home
  2. Docs
  3. Oracle 19c PL/SQL
  4. 2 Control Statements
  5. WHILE Loop

WHILE Loop

--Printing 1-5 in a single line

SET SERVEROUTPUT ON;
DECLARE
  V_Num NUMBER := 1;      --This variable will print the numbers.
  V_Output VARCHAR2(100); --This will arrange the numbers in a single line.
BEGIN
  WHILE V_Num<6
    LOOP
      V_Output :=V_Output||'  '||V_Num;
      V_Num :=V_Num+1;
    END LOOp;
  DBMS_OUTPUT.PUT_LINE(V_Output);
END;
/
/* Write a program to print above output using WHILE loop
   1
   1  2
   1  2  3
   1  2  3  4
   1  2  3  4  5
*/

DECLARE
  V_Num NUMBER :=1; --This variable will print the numbers.
  V_Output VARCHAR2(100); --This will arrange the numbers in a single line.
BEGIN
  WHILE V_Num<6
    LOOP
      V_Output :=V_Output||'  '||V_Num;
      V_Num :=V_Num+1;
      DBMS_OUTPUT.PUT_LINE(V_Output);
    END LOOp;
END;
/
--Reverse a number and check for Palindrome

DECLARE
  V_Num NUMBER :=&GNumber; --Original number which is to be checked for Palindrome.
  V_Reverse NUMBER; --Stores the reverse of the inputted number. 
  V_Temp NUMBER; --Stores one copy of the original number.
BEGIN
  DBMS_OUTPUT.PUT_LINE('The original number is : '||V_Num);
  V_Temp :=V_Num;
  V_Reverse :=0;
  WHILE V_Temp <>0
    LOOP
      V_Reverse :=V_Reverse*10+MOD(V_Temp, 10);
      V_Temp :=TRUNC(V_Temp/10);
    END LOOP;
    DBMS_OUTPUT.PUT_LINE('Reverse of the number is : '||V_Reverse);
    IF V_Num =V_Reverse THEN
      DBMS_OUTPUT.PUT_LINE('The number is a Palindrome');
    ELSE
      DBMS_OUTPUT.PUT_LINE('The number isn''t a Palindrome');
    END IF;
 END;
/
----Display all the Months between two given dates using WHILE Loop.

DECLARE
  V_Date1 DATE :='&GiveDate1'; --Signifies the Lower date.
  V_Date2 DATE :='&GiveDate2'; --Signifies the Upper date.
  BEGIN
    DBMS_OUTPUT.PUT_LINE('Months between '||V_Date1||' and '||V_Date2||' are :');
    WHILE V_Date1 <V_Date2
      LOOP
        DBMS_OUTPUT.PUT_LINE(TO_CHAR(V_Date1, 'Month'));
        V_Date1 :=ADD_MONTHS(V_Date1, 1);
     END LOOP;
END;
/
Was this article helpful to you? Yes No

How can we help?