Factorial Code works but why - factorial

I'm solving a factorial problem where the function takes a number and returns the factorial of that number.
The problem I'm running into is that the code works but I don't know why. There are no loops to call it back after the code is executed and I'm not even sure where the current value is being stored.If I am correct the I assume the function is re-running every time it hit the return and it is running with a value of n-1 so one number less than the previous time it ran, however, I still do not see how the value is getting stored to multiple each number by the current value. Even if I log the current value of n after every run all I get is the numbers 10 down to one. I would think the current value would change to the multiplied value.
Again this code works perfectly I just need to understand why.
function factorial(n) {
if (n === 0) {
return 1;
}
console.log(n);
return n * factorial(n - 1);
}
factorial(10);

What you have here is a recursive function - a function which calls itself. You also need to keep in mind the "scope" of the variables in the function.
The scope of the parameter "n" is local to the function. Every time the function is called, the new variable is created. The scope of each variable is the function execution.
1: function factorial(n) {
2: if (n === 0) {
3: return 1;
4: }
5: console.log(n);
6: return n * factorial(n - 1);
7: }
Example:
Parameter Value = 0
Hence, n = 0
Execute factorial(0)
1. line 1: variable n = 0
2. line 2: check if n = 0
3. line 3: return 1
Example:
Parameter Value = 2
Hence, n = 2
Execute factorial(2)
1. line 1: variable n = 2 (scope = execution #A)
2. line 5: console log n = 2
3. line 6: return 2 * factorial(2-1) // Function calls itself
4. line 1: variable n = 1 (scope = execution #B)
5. line 5: console log n = 1
6. line 6: return 1 * factorial(1-1) // Function calls itself
7. line 1: variable n = 0 (scope = execution #C)
8. line 3: return 1 // #C returns 1
9. return 1 * 1 // #B returns 1 * 1 (from #C)
10. return 2 * 1 // #A returns 2 * 1 (from #B)

Related

Making a collatz program and end it after 500 runs

This is my script. How do i add so the loop ends if it has to run 500 times or more?
x=0
while x<=500:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
x=x+1
else:
print('Loop ended)
break
This is the collatz equation but it is not always sure that it ends up on 1. So I need to rewrite my program so that the loop ends if the number series will be longer than 500 numbers.

I am getting unexpected output

I assumed the output to be '0' for the following code but, I am getting the output as '3'.
#include<stdio.h>
int num_digit(int n);
int num_digit(int n)
{
if (n == 0)
return 0;
else
return 1 + num_digit(n/10);
}
int main() {
int k = num_digit(123);
printf("%d\n",k);
return 0;
}
The following link provides an excellent source for learning C Recursion and as #MFisherKDX pointed out help solve my confusion.
https://www.programiz.com/c-programming/c-recursion
After each time the recursion happens it returns a value.
adding up all the values :
0+1 = 1
1+1 = 2
2+1 = 3
gives the answer as 3.
This is basic recursion. Just try to create a recursion tree for the program that you have written and you should be able to figure out why is the output that you see coming as 3.
You are expecting 0 as answer, only based on the last recursive call (terminating condition), but when a recursive call happens, there is a concept of activation records which are maintained in the form of Stack data structure.
The recursion tree will look something like what is shown in Recursion Tree for shared code
num_digits(123) = 1 + num_digits(12)
num_digits(12) = 1 + num_digits(1)
num_digits(1) = 1 + num_digits(0)
num_digits(0) = 0
Using substitution:
num_digits(123) = 1 + (1 + (1 + (0)))
Please follow the parenthesis above clearly and you should be able to absolutely understand the output that you were getting out of the code that you wrote.
Recursion stack for your code is like below
1 + num_digit(123/10);
1 + num_digit(12/10);
1 + num_digit(1/10); //at this point your code will return 0 for num_digit(1/10)
and backtracking is like below
1+0=1
1+1=2
1+2=3
Hence the final answer is 3

Recursive function descending output

void prikaz(int k, int n)
{
printf("%d\t",k);
if(k<n)
prikaz(k+1,n);
printf("%d\t",k);
}
prikaz(2,6);
I cant wrap my head around the output of this recursive loop, i can follow through till numbers start to descend but i dont understand why they descend.
The reason is because of the last line in the function, which prints the value of k after the recursive call has returned/finished. This will print the value as it was before the +1, i.e. the original value before the call.
However, it only does that part after all the recursive calls are complete.
Basically, when k<n is no longer true, then it will start to do the last printf call, then return to the previous function call and do that ones last printf (which will be the value of k before it was incremented) and it will repeat until all previous calls are complete.
It's quite hard to explain, you just need to step through it more carefully. Using a debugger would help greatly.
Maybe this helps explain it better:
// call 1 (k = 2)
// call 1 print 2
// call 2 (k = 3)
// call 2 print 3
// call 3 (k = 4)
// call 3 print 4
// call 4 (k = 5)
// call 4 print 5
// call 5 (k = 6)
// call 5 print 6
// k<n is false, so no more recursive calls.
// call 5 print 6
// call 4 print 5
// call 3 print 4
// call 2 print 3
// call 1 print 2

C switch case with function

can someone explain me this code?
I cant understand why printed value is 8 in this code
can someone explain it to me
#include <stdio.h>
int f(int i){
switch (i){
case 0 :
return 0;
case 1:
case 2:
return 1;
default:
return f(i-2)+f(i-1);
}
}
void main(void) {
printf("%d", f(6));
}
Maybe you just need to step through the code in a debug run, but this is why you have f(6)=8
step1: f(6)
step2: f(6-2) +f(6-1)
step3: f(4-2)+f(4-1) +f(5-2) +f(5-1)
step4: f(2) +f(3-2)+f(3-1)+f(3-2)+f(3-1)+f(4-2)+f(4-1)
step5: 1 +1 +1 +1 +1 +1 +f(3-2)+f(3-1)
step6: 1 +1 +1 +1 +1 +1 +1 +1
final: 8
This is a recursive function to implement the Fibonacci sequence
Lets consider a simpler scenario (in order to shorten response length) of if we were to call the function with argument of 4 : f(4)
Stepping through it we find:
Called f(4)
Hit default case statement to call f(2) + f(3)
The f(2) call will hit the case statement for 2 and return 1
The f(3) call will hit the default case statement and call f(1) + f(2)
Both f(1) and f(2) will hit their respective case statements and return 1
We now know the f(3) call returns f(1) + f(2) = 1 + 1 = 2
We now know the f(4) call returns f(2) + f(3) = 1 + 2 = 3
I would recommend the same process to see why a call of f(5) would return 5. And then using the fact that f(4) = 3 and f(5) = 5, you can understand why f(6) = f(4) + f(5) = 8.
This is a recursive implementation the Fibonacci sequence, where each number is the sum of the two preceding numbers.
The switch statement works as follows:
If i is 0, return 0
If i is 1 or 2, return 1
Otherwise, return the sum of f(i-2) and f(i-1) - this eventually boils down to the two base cases above.
This is a recursive function which contains a switch case. Generally, in a Switch case, you need a statement breaker like break or return so that only that specific case executes correctly. Since in your code case 1 and case 2 return to same value ie 1 your code breaks down as a sum of 8 1s and final sum is 8.

C function output

Can anyone tell me the reason of getting 0 1 2 0 as output of below program?
#include <stdio.h>
main() {
e(3);
}
void e(int n) {
if(n>0) {
e(--n);
printf("%d",n);
e(--n);
}
}
Output is 0 1 2 0
Here' the flow of execution after e(3) is called from main.
e(3)
e(2)
e(1)
e(0) ... return
n is now 0
print n. results in output 0
e(-1) ... return
n is now 1
print n. results in output 1
e(0) ... return
n is now 2
print n. results in output 2
e(1)
e(0) ... return
n is now 0
print n. results in output 0
e(-1) ... return
return
And you see the output
0 1 2 0
I'm assuming the following is what you want:
#include <stdio.h>
void e(int);
int main()
{
e(3);
return 0;
}
void e(int n)
{
if(n > 0) {
e(--n);
printf("%d", n);
e(--n);
}
}
This is an example of a recursive function - a function calling itself. Here, at each call the parameter is decremented and the function is again called until the condition n > 0 is not met. Then, the printf("%d", 0) happens. Now the second e(--n) will have no effect until n is at least 2, since the if condition cannot be passed with a value of n less than 1. Further printf()s happen in the reverse order of the call as the function calls are removed from the stack. When the value gets to 2, the second e(--n) gets a chance to make an effect thus printing 0.
You need to learn about recursion (if you still haven't) and then you can get a good picture of how things happen. Also, it will help you if learn more about how the stack is set up when a function is called, and later returned.
The 'flow' goes as follows:
main -> e(3)
e(3) -> IF(3>0)
{
// n is pre-decremented to 2
e(2) -> IF(2>0)
{
// n is pre-decremented to 1
e(1) -> IF(1>0)
{
// n is pre-decremented to 0
e(0) -> 0 is not > 0 so this call does nothing.
// n is still 0 in this function call so...
printf(0) <-- The first '0' in the output
// n is pre-decremented to -1
e(-1) -> -1 is not > 0) so this call does nothing.
}
// n is still 1 in this function call so...
printf(1) <-- The '1' in the output
// n is pre-decremented to 0
e(0) -> 0 is not > 0 so this call does nothing
}
// n is still 2 in this function call so...
printf(2) <-- The '2' in the output
// n is pre-decremented to 1
e(1) -> (1 is > 0)
{
// n is pre-decremented to 0
e(0) -> 0 is not > 0 so this call does nothing
// n is still 0 in this function call so...
printf(0) <-- The second '0' in the output
// n is pre-decremented to -1
e(-1) -> -1 is not > 0 so this call does nothing
}
}
It helps if you set the code out more clearly:
#include<stdio.h>
main()
{
e(3);
}
void e(int n)
{
if(n>0)
{
e(--n); // First recursion here, but with n=n-1 on entry to the call.
printf("%d",n); // outputs (original value of n) - 1.
e(--n); // Second recursion here, now with n=n-2 on entry to the call.
}
}
After denesting the code the reason for the results can be deduced in a single run in a debugger.
e() is recursive and called once before the print and once after. So before you hit your print statement you'll have to go through e again, and again, and again till it finally hits 0.
After that things start unlooping and you'll see prints popping up but it's still a big recursive mess because of the second call to e(n) in which n dips into the negative. I was rather grateful n was signed because if it was unsigned it would loop round to 2^32 and the program would get stuck in, pretty much, an infinite loop.
So yeah, TL;DR: run it through a debugger and learn from the FUBAR a recursion like this can cause.

Resources