Recursive function descending output - c

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

Related

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.

Factorial Code works but why

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)

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.

Recursive Confusion

Hello everyone I had a tough time understanding recursive function calls and just when I thought I have understood them, I saw a question which made me realized that I am wrong
I am not able to understand the flow of the program
#include <stdio.h>
void fun(int n)
{
if(n>0)
{
fun(--n);
printf("%d\n",n);
fun(--n);
}
}
int main(void) {
int a;
a=3;
fun(a);
return 0;
}
This is the function call for your function when n = 3
f(3)
.f(2) [1]
..f(1) [1]
...f(0) [1]
...Print 0
...f(-1) [2]
..Print 1
..f(0) [2]
.Print 2
.f(1) [2]
..f(0) [1]
..Print 0
..f(-1)[2]
Where . represent the depth of stack and 1 and 2 specify whether its first recursive call from the loop or second.
Because
f(3)
becomes
f(2)
print 2
f(1)
which inturn becomes
f(1)
print 1
f(0)
print 2
f(0)
print 0
f(-1)
Which finally becomes
f(0)
print 0
f(-1)
print 1
f(0)
print 2
f(0)
print 0
f(-1)
Removing all the f(n) when n <= 0
print 0
print 1
print 2
print 0
Let's try to understand it with case n=2 and then you should be able to generalize.
fun (2):
What happens inside (flow):
1) n=2: if(n>0) is true and fun(--n) is called with n set to value 1 due to --; (see step below).
2) n=1: Now n=1: again if(n>0) is true and fun(--n) is called with n=0. See step below.
3) n=0: Now n=0; if(n>0) is false, so we return.
I think here is your confusion. From step 3 you are thrown back
at step 2 (not step 1). You are thrown actually in step 2 after fun(--n) call - so printf is called with value of n=0, due to decrement.
Then again in same place (after printf) fun(--n) is called with value n=-1 however, which will also exit - and eventually you will be thrown at the beginning.
I would draw a "call tree" to help visualize the program.
The function has those parts
decrement n, call, print, decrement n, call
now you can draw this:
0 -1
1->0, print 0, 0->-1, 0
2->1, print 1, 1->0, 1->0, .....
3->2, print 2, 2->1, .....
Start at the bottom left, and go up one line for each call. The program executes from left to right, and you can clearly see the order of the numbers printed.
Here is what happens (pseudocode):
n = 3
fun(3);
n = 2
fun(2); // first fun(--n)
n = 1
fun(1); // first fun(--n)
n = 0
fun(0); // first fun(--n)
return;
print 0
n = -1
fun(-1); // second fun(--n)
return;
return;
print 1
n = 0
fun(0); // second fun(--n)
return;
return;
print 2
n = 1
fun(1); // second fun(--n)
n = 0
fun(0); // first fun(--n)
return;
print 0
n = -1
fun(-1); // second fun(--n)
return;
return;
return;
return;
I believe the cause of confusion is your assumption that the same "n" is used by every call to the function fun(). In fact, that's not the case, since in the C language, argument are passed by value. That is, when fun(3) calls fun(2), a new n is created - specific to one instance of fun(2). Thus after the call to fun(3) within fun(2), the value of n is 2, not or -1.
You should therefore expect...
fun(1) to print 0
fun(2) to print 1
fun(3) to print 2
fun(1) (called from the second call to fun(2)) to print 0
and that's it.
The output of the program can be understood by iteratively expanding the function calls and removing the conditions; in a pseudocode-manner, this can be done as follows.
fun(3)
Can be expanded to the following.
if(3>0)
{
fun(2);
printf("%d\n",2);
fun(1);
}
In the follwing steps, the if condition is omitted if it will evaluate to false.
fun(1);
printf("%d\n",1);
fun(0);
printf("%d\n",2);
fun(0);
printf("%d\n",0);
fun(-1);
The calls to fun with non-positive arguments can be omitted as they will generate no output.
fun(1);
printf("%d\n",1);
printf("%d\n",2);
printf("%d\n",0);
Further expansion yields the following sequence.
fun(0);
printf("%d\n",0);
fun(-1);
printf("%d\n",1);
printf("%d\n",2);
printf("%d\n",0);
This can be again reduced to the following sequence.
printf("%d\n",0);
printf("%d\n",1);
printf("%d\n",2);
printf("%d\n",0);
So in total, the output will be as follows.
0
1
2
0
I hope this answers your question; however, it does not provide an intuitive way of describing the generated output.
To understand the recursive flow you can instrument your code with few printfs like below. This will show the sequence of flow of function using indentation.
#include <stdio.h>
void printSpace(int num)
{
while(num > 0)
{
printf(" ");
num--;
}
}
int NumSpace = 0;
void fun(int n)
{
printSpace(NumSpace);
printf("fun(%d)\n", n);
NumSpace += 4;
if(n>0)
{
fun(--n);
printSpace(NumSpace);
printf("%d\n",n);
fun(--n);
}
NumSpace -= 4;
}
int main(void) {
int a;
a=3;
fun(a);
return 0;
}
Result:
fun(3)
fun(2)
fun(1)
fun(0)
0
fun(-1)
1
fun(0)
2
fun(1)
fun(0)
0
fun(-1)
Hope this helps.

how to do a postscript recursive loop

i'm new to postscript. What is a format for a function that calls itself recursively. lets say I have a function called squares that prints out a square.
5 square // prints out 5 squares
I think 5 will be a the top of the stack. Each repititon will decrease that number until 0 is met. If there is an easier way to do this, let me know.
%!PS-
%
% int myfunction -
% Executes recursively 'int' times
%
/myfunction {
dup == % Print out the current 'int' just to show we're doing something
1 sub % decrement 'int' by 1
dup 0 gt % copy 'int' and test to see if its 0
{ % not 0, so recurse, the copy on the stack is the new 'int'
myfunction % execute recursion
} {
pop % The copy of 'int' was 0,so remove the copy from the stack
} ifelse
} bind def
5 myfunction
Or you could just use loop to execute a code block 5 times.
/go
{
/cnt { 1 add dup == } def
0
{ cnt } loop
} def
% start by calling go
go
a simple infinite counter that should you get started

Resources