Thursday, November 17, 2011

Check Number is Armstrong in PL/SQL Programming

It is a sample pl/sql program to take input a number from user and it checks accepted number is Armstrong or not.

Aim - PL/SQL program to check whether number is Armstrong or not.

Program:-
declare
  pnum number(5);
  tot number(5);
  lp number(3);
  tmp number(5);
begin
  pnum:=&pnum;
  tmp:=pnum;
  tot:=0;
  while tmp>0
  loop
    lp:=tmp mod 10;
    tot:= tot + (lp*lp*lp);
    tmp:=floor(tmp/10);
  end loop;
  if(tot like pnum) then
    dbms_output.put_line(pnum||' is armstrong.');
  else
    dbms_output.put_line(pnum||' is not armstrong.');
  end if;
end;


Output: -
Enter value for pnum: 153
old 7: pnum:=&pnum;
new 7: pnum:=153;
153 is armstrong.

Reverse a Number in PL/SQL Programming

It is a sample PL/SQL program to take input a number form user and print reverse of accepted number.

Aim - PL/SQL Program to accept a number from user and print number in reverse order.

Program: -
declare
  num1 number(5);
  num2 number(5); 
  rev number(5);
begin
  num1:=&num1;
  rev:=0;
  while num1>0
  loop
    num2:=num1 mod 10;
    rev:=num2+(rev*10);
    num1:=floor(num1/10);
  end loop;
  dbms_output.put_line('Reverse number is: '||rev);
end;


Output: -
Enter value for num1: 12345
old 8: num1:=&num1;
new 8: num1:=12345;
Reverse number is: 54321



Basic LOOP Program in PL/SQL

It is a PL/SQL program which show how to use basic loop concept in PL/SQL block.

Aim - PL/SQL program to print 1 to 10 using basic loop.


Sample Program: -
declare
  num number(3);
begin
  num:=1;
  loop
     dbms_output.put_line(num);
     num:=num+1;
     exit when num>10;  
  end loop;
end;

Output: -
1
2
3
4
5
6
7
8
9
10

PLSQL FOR Loop Example

It is a basic FOR loop example program which is demonstrate how to use FOR loop in PL/SQL block. FOR loop use in PLSQL is quite differ with C program FOR loop syntax. In PLSQL you should specify the range of integer to execute the sequence of statements.

Syntax
FOR variable IN start..end
LOOP
 PL/SQL block statements
END LOOP;


Sample Example to print number 1 to 10 using FOR loop.

Aim - pl/sql program to print 1 to 10 using FOR loop


Program Code: -
declare
  num number(3);
begin
  for num in 1..10
 loop
  dbms_output.put_line(num);
 end loop;
end;


Output: -
1
2
3
4
5
6
7
8
9
10



Another example to print 1 to 10 in reverse order using FOR loop.
Syntax
FOR variable IN REVERSE start..end
LOOP
PL/SQL block statements
END LOOP;



Aim - program to print 1 to 10 in reverse order using FOR loop.

Program Code: -
declare
  num number(3);
begin
  for num in  REVERSE 1..10
 loop
  dbms_output.put_line(num);
 end loop;
end;


Output: -
10
9
8
7
6
5
4
3
2
1