# Recursive function in solidity?

I need to call a recursive function with if statements. Is this possible in Solidity? Please provide an example.

It is possible to use recursive functions in Solidity. The following is a simple recursive function in solidity

``````pragma solidity ^0.5.12;

contract Test {
uint x;
function set(uint y) public {
x = y;
}

function factorial(uint y) internal pure returns(uint){
if (y == 1){
return y;
} else {
return y * factorial(y-1);
}
}

function get() public view returns(uint){
return factorial(x);
}
}
``````

But please be aware that you should know what you are doing since recursive functions can end up costing huge gas and cause the transaction to revert atomically.

• One thing worth to note is : Gas requirement of function Test.get() high: infinite. If the gas requirement of a function is higher than the block gas limit, it cannot be executed. Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage) Oct 11, 2019 at 13:19
• I have mentioned the word of caution in my answer. Oct 11, 2019 at 13:22
• Worth noting that if you want this to work externally as well, you need to switch the function to "public". Mar 11, 2021 at 16:30

Fibonacci is perfect example to illustrate the recursion(tail):

Mathematically, the Fibonacci sequence is a recursive function that adds the previous elements to obtain the next element, Like below:

``````Fn = Fn-1 + Fn-2
``````

``````function fib(uint n) public view returns(uint) {
if (n <= 1) {
return n;
} else {
return this.fib(n - 1) + this.fib(n - 2);
}
}
``````

Note: Please avoid loops in your functions or actions that modify large areas of storage (this includes clearing or copying arrays in storage)