Skip to Main Content

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Austin.

Asked: October 25, 2016 - 1:28 pm UTC

Last updated: October 26, 2016 - 7:51 am UTC

Version: Oracle 11g

Viewed 1000+ times

You Asked

Write a PL/SQL block that uses looping to display the value of the number two (2) raised to a power. The power should be given as a local variable called lv_power. For example, if the variable is initialized to 5, the output would be 2 raised to the 5th power which is 32. Allow a maximum power of 32, thus 2 raised to the 32nd power is 4,294,967,296. You cannot use the power() function OR the raising to power operator **

and Chris said...

Let me guess, this is an interview question, right?

It's a simple loop operation...

declare
  val pls_integer := 2;
  res pls_integer := 1;
  pwr pls_integer := 5;
begin
  for i in 1 .. pwr loop
    res := val * res;
  end loop;
  dbms_output.put_line(res);
end;
/

32

Rating

  (3 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

No Output

Austin, October 25, 2016 - 11:43 pm UTC

When I run this I am not getting any output.
Connor McDonald
October 26, 2016 - 12:58 am UTC

Do "set serveroutput on" first.

SQL> declare
  2    val pls_integer := 2;
  3    res pls_integer := 1;
  4    pwr pls_integer := 5;
  5  begin
  6    for i in 1 .. pwr loop
  7      res := val * res;
  8    end loop;
  9    dbms_output.put_line(res);
 10  end;
 11  /

PL/SQL procedure successfully completed.

SQL> set serveroutput on
SQL> declare
  2    val pls_integer := 2;
  3    res pls_integer := 1;
  4    pwr pls_integer := 5;
  5  begin
  6    for i in 1 .. pwr loop
  7      res := val * res;
  8    end loop;
  9    dbms_output.put_line(res);
 10  end;
 11  /
32

PL/SQL procedure successfully completed.




Or. .

Ghassan, October 26, 2016 - 4:58 am UTC

Use the recursive with clause
Start with 2 power 0 union the rest
Where n less than input :1..

Connor McDonald
October 26, 2016 - 7:51 am UTC

Yes, you could do that, but you'd probably be marked 'wrong' given the that question is stated as:

"Write a PL/SQL block that uses looping to display the value of the number two (2) raised to a power."

:-)

Thank you

A reader, October 26, 2016 - 2:59 pm UTC

It's working.

Thank you

More to Explore

DBMS_OUTPUT

More on PL/SQL routine DBMS_OUTPUT here