PHP Tutorial

PHP Examples

PHP Practice

PHP program to calculate the power of a number using recursion

Here, we are going to learn how to calculate the power of a given number using recursion in PHP?
By Nidhi Last updated : December 22, 2023

Prerequisites

To understand this example, you should have the basic knowledge of the following PHP topics:

Problem statement

Write PHP script to calculate the power of a given number using the recursion function.

For example: The power 3 of number 5 is 125.

Calculating power using recursion

In this program, we will calculate the power of the specified given number using recursion. A recursion function is a very useful programming concept in which a function calls itself in its own definition.

Recursion function definition to calculate the power

Write a function, pass two arguments number and its power, make it recursive by calling itself in the definition. Below is the recursion function to calculate the power:

//using recursion.
function Power($num, $p)
{
    if ($p == 0) return 1;
    return $num * Power($num, $p - 1);
}

PHP code to calculate power using recursion

The source code to calculate the factorial of a given number using recursion is given below. The given program is compiled and executed successfully.

<?php
//PHP program to calculate the power of a number
//using recursion.
function Power($num, $p)
{
    if ($p == 0) return 1;
    return $num * Power($num, $p - 1);
}

$result = Power(5, 3);
echo "Result is: " . $result;
?>

Output

Result is: 125

Explanation

In the above program, we created a recursive function Power() to calculate the power of a given number, The Power() function returns the power of a specified number to the calling function, in our program, we calculated the power 3 of number 5 that is 125.

PHP Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.