In: Computer Science
Consider the function computational as implemented below.
(a) Describe what the function does.
(b) What is the output of this function.
(c) Explain the recursive action. (While describing the recursive
action define what recursion is and how does recursion work.)
int computational(int n){
if (n < 10) && (n > -10))
return 1;
else
return 1 + computational(n/10);
}
A good variant expression is “the number of digits in n,” with the
threshold of 1.
Consider the following function:
(a) Describe what the provided function does:
• The above function counts the number of digits in input integer n.
• The provided function works recursively to find the number of digits in positive or negative input.
If the input is 846 then the output will be 3.
If the input is 9782536 then the output will be 7.
If the input is 8 then the output will be 1.
If the input is -26 then the output will be 2.
(b) Output of the function:
Output:
(c) Explain the function's recursive action:
• Recursion:
• The process or technique in which a function calls or references to itself is called recursion.
• This procedure enables function code to repeat several times.
• How recursive function works:
• Recursive function generally have two cases:
Base case: Base case returns some static value to the function.
Recursive case: Recursive case recursively calls the function.
• General structure of recursive function:
void myfunction()
{
myfunction(); // Function calls or references to itself.
}
int main()
{
myfunction();
}
• Recursive action of provided function:
Let's consider the input n = 100
int computational(int n) // n = 100
{
if (n < 10) && (n > -10)) // if condition is false go to else
return 1;
else
return 1 + computational(n/10); // 1 + computational(100/10)
}
call function computational() again:
int computational(int n) // n =10 ( n/10 = 100/10 = 10)
{
if (n < 10) && (n > -10)) // if condition false go to else
return 1;
else
return 1 + computational(n/10); // 1 + computational(10/10)
}
call function computational() again:
int computational(int n) // n =1 ( n/10 = 10/10 = 1)
{
if (n < 10) && (n > -10)) // if condition is true and return 1
return 1;
else
return 1 + computational(n/10);
}
Function call 3: computational(1) = 1
Function call 2: computational(10) = 1 + 1 = 2
Function call 1: computational(100) = 1 + 2 = 3
Output: 3