Home »
Aptitude Questions and Answers »
PHP Aptitude Questions and Answers
PHP Recursion Aptitude Questions and Answers
PHP Recursion Aptitude: This section contains aptitude questions and answers on Recursion.
By Nidhi Last updated : December 15, 2023
This section contains Aptitude Questions and Answers on PHP Recursion.
1) There are the following statements that are given below, which of them are correct about recursion in PHP?
- When a function called by itself then it is known as recursion.
- PHP does not support indirect recursion.
- We can implement almost all programs using recursion that can be done by loops.
- All of the above
Options:
- A and B
- A and C
- B and C
- D
Correct answer: 2
A and C
Explanation:
The process of calling a function by itself is known as recursion, we can implement almost all programs using recursion that can be done by loops or iterative statements.
2) Which of the following is/are correct types of recursion in PHP?
- Direct recursion
- Indirect recursion
- Both
- None
Correct answer: 3
Both
Explanation:
Both direct and indirect recursions are correct types of recursion in PHP.
Direct Recursion: Function calls itself directly.
Indirect Recursion: Function calls itself using other function, like fun1() calls fun2() and fun2() calls fun1(), it means fun1() indirectly calls itself.
3) What is the correct output of the given code snippets?
<?php
function fun($num)
{
if ($num < 5)
{
echo "$num ";
$num++;
fun($num);
}
}
fun(0);
?>
- 1 2 3 4
- 1 2 3 4 5
- 0 1 2 3 4
- Infinite
Correct answer: 3
0 1 2 3 4
Explanation:
The above code will print "0 1 2 3 4", here we pass value 0 to the function, it will print values 0 to 4, and then when the value becomes 5 conditions get false and the program gets terminated.
4) What is the correct output of the given code snippets?
<?php
function fun1($num)
{
if ($num < 5)
{
print "$num ";
$num++;
fun2($num);
}
}
function fun2($num)
{
fun1($num);
}
fun1(0);
?>
- 1 2 3 4
- 1 2 3 4 5
- 0 1 2 3 4
- Infinite
Correct answer: 3
0 1 2 3 4
Explanation:
The above code will print "0 1 2 3 4", here we used indirect direction, here fun1() calls fun2() and fun2() calls fun1(), then we can say fun1() indirectly calls itself.
5) What is the correct output of the given code snippets?
<?php
function my_rec_fun($num)
{
if ($num < 0) return -1;
if ($num == 0) return 1;
return ($num * my_rec_fun($num - 1));
}
echo my_rec_fun(4);
?>
- 120
- 24
- 16
- None of the above
Correct answer: 2
24
Explanation:
The above function calculates the factorial of a given number, the factorial of 4 is 24.