Simple Recursion output calling recursion twice - c

This is how I tried it. The main part uses fun(9). So 9 does not equal or less than one. And it calls fun(9/3) two times and prints n which is 9. Where am I wrong here?
#include <stdio.h>
void fun(int n){
if(n<=1) printf("*");
else{
fun(n/3);
fun(n/3);
printf("%d",n);
}
}
int main(void){
fun(9);
return 0;
}

When called as fun(9), the code shown does print **3**39.
The first call has n == 9.
Consequently, if calls fun(3), then fun(3) again, and then prints 9.
The first of the two calls fun(3) calls fun(1), which prints a *, then calls fun(1) again and prints another *, and then prints 3.
The second of the two calls does the same.

Your output should be
* * 3 * * 3 9

If you can't see how it works, then do it by hand and fill in the values instead of the variable name:
Pass 1:
void fun(9){ // first pass n=9
if(9<=1) printf("*"); // nope, that's not true
else{
fun(9/3); // call the function again with n = 9/3 = 3
Pass 2:
void fun(3){ // second pass n=3
if(3<=1) printf("*"); // nope, that's not true
else{
fun(3/3); // call the function again with n = 3/3 = 1
Pass 3:
void fun(1){ // third pass n=1
if(1<=1) printf("*"); // yes! so print first *
else{ // this function is only an if and an else, we hit the if
// so it just drops out now
So pass #3 and we hit the lowest level of the recursive call, now Pass 2 will continue execution where it left off:
Pass 2b:
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // next recursive call, again with n = 1
Now this will repeat the "pass #3" code, again printing a second *, then it will return and continue execution where it left off:
Pass 2c:
void fun(3){ // second pass n=3 (did this already)
if(3<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(3/3); // call the function with n = 1 (did this already)
fun(3/3); // call again with n = 1 (did this already)
printf("%d", 3); // print 3
At this point the output is: **3 Pass #2 is now complete so we go all the way back up and resume Pass #1 where it left off:
Pass 1b:
void fun(9){ // first pass n=9 (did this already)
if(9<=1) printf("*"); // nope, that's not true (did this already)
else{
fun(9/3); // call the function again with n = 3 (did this already)
fun(9/3); // now call the function again with n = 9/3 = 3
From here you can see that we're going to repeat the Pass 2 logic producing another **3 then we'll return to Pass1 a final time to print the 9
A final output of: **3**39

Related

Why does function not work when I add a function in it?

I am new at recursive functions.
int display(int num) {
if(num) {
display(num-1);
}
else {
return 0;
}
printf("\t%d", num);
}
When I run display(5), i can get "1 2 3 4 5" output as i want.
BUT:
When I add another function in this code and make some changes on the display() function and run the display(5) command it gives no output.. Here is the other code:
int bunnyEars2(int line) {
if(line == 0) {
return 0;
}
if(line % 2 == 1) {
return 2 + bunnyEars2(line-1);
}
else {
return 3 + bunnyEars2(line-1);
}
}
int display(int n) {
if(bunnyEars2(n)) {
display(bunnyEars2(n-1));
}
else {
return 0;
}
printf("\n%d", bunnyEars2(n));
}
I want to take bunnyEars2(1), bunnyEars2(2), bunnyEars2(3), bunnyEars2(4), bunnyEars2(5) outputs from display(5) command. But it gives no output. Can you help me out with this?
When you call display(5) it calls display(bunnyEars2(5)) which is display(12) => infinite loop
display(n) calls display(bunnyEars2(n-1)) and for every n>=2, bunnyEars2(n-1) > n so that you will get an infinite loop.
Other people have already given the reason for why this code is causing issues so I'll go into how to potentially look the causes of issues like this in the future.
When writing a recursive function, It is important to identify the various cases for your function. Each recursive function will have a set of cases which cause the function to call itself (recursive cases) and a set of functions in which the function will not call itself (base cases). In the case of the display function given in the first example. The recursive case is -- num has a non zero value, and the base case is -- num has a value of 0. A recursive function will only cease recursing if a function call hits a base case causing the recursive function calls to resolve rising up the call stack. Under any circumstance, any call to a recursive function does not lead a call of the function resulting in the execution of the base case, the call to the function will not resolve resulting in infinite recursion.
This infinite recursion is occurring in your second version of the display function. Look closely at the recursive case of your second display function.
if(bunnyEars2(n)){
display(bunnyEars2(n-1));
}
How would the value of bunnyEars2(n-1) compare to the value of n? Examine whether this recursive case will result in a calling of the function that executes a base case.
If you have access to a debugger and know how to use it, try stepping through the function and see what path it takes through the code. If you do not have access to a debugger, get some paper and a pencil and walk through the execution of your function by hand. This should give you a better idea about what your code is doing and how a problem might arise.

How does the for loop run in such a case?

#include <stdio.h>
int f1(){
static int val=11;
return --val;
}
int main()
{
for( f1(); f1(); f1()){
printf("%d",f1());
}
}
The output of the program is :
8 5 2
Could someone explain me what does for(f1();f1();f1()) do?
#include <stdio.h>
int foo(void) {
static int val = 11;
return --val;
}
int main(void) {
int (*f1)(void) = foo; //4 function pointers to the same function
int (*f2)(void) = foo;
int (*f3)(void) = foo;
int (*f4)(void) = foo;
for (f1(); f2(); f3()) {
printf("%d", f4());
}
}
The execution goes like this
val = 11
f1() 10
f2() 9 "true"
f4() print 8
f3() 7
f2() 6 "true"
f4() print 5
f3() 4
f2() 3 "true"
f4() print 2
f3() 1
f2() 0 "false"
For easier understanding I'll talk about functions as such:
for (A(); B(); C()) {
printf("%d", D());
}
So understand that all A B C and D are calls to f1() but I want to be able to differentiate them.
1st thing to understand is how are the "parameters" of for working.
1st one is the init part, it will be executed once only, before the evaluation of the first condition.
2nd one is the condition part, it will be executed before every loop, to check if it needs to keep looping or stop.
3rd one is the conclusion part, it will be executed after every loop, before the next evaluation of the condition.
We can then understand that your program will execute in this order:
call A() to initialize the for loop => val = 10;
call B() to check condition => val = 9
call D() in your printf => val = 8 gets printed
call C() to end an iteration => val = 7
call B() to check condition => val = 6
call D() in your printf => val = 5 gets printed
call C() to end an iteration => val = 4
call B() to check condition => val = 3
call D() in your printf => val = 2 gets printed
call C() to end an iteration => val = 1
call B() to check condition => val = 0 condition ends
The C for loop contains 3 items:
the initialisation
the condition
the incrementation
A for loop run until the condition is equal to either 0 or null.
You enter the loop, it call f1() a first time in the initialisation so val equal 10
At each iteration, it will call f1() three time, to check the condition, to do the increment part and in the printf call. Thus at each iteration we have val = val - 3
Once val == 0 you exit the loop.
Note that it only work because val is static thus not being reinitialised at each call of f1()

Is it necessary to put return in a void recursion?

Feel free to make this post as a duplicate if the question asked already, I haven't found a post same as this
As far as I know that there's no need to return in a void function, e.g:
void ex () {printf ("Hi\n");}
But, is it fine if there's no return in a void recursion? What I'm thinking is, the program will keep calling func (num-1) until it reaches 0 and it returns so it doesn't print 0 to the output, and I need return at the end of the function so after the recursion call is done, you go back to the previous func () immediate caller.
Here's the code,
#include <stdio.h>
void func (int num)
{
if (!num) return;
func (num-1);
printf ("%d\n", num);
return; //Is it necessary to put return here?
}
int main ()
{
func (10);
return 0;
}
Output,
1
2
3
4
5
6
7
8
9
10
Without the last return, it works just fine too, or am I missing something?
A function with return type void doesn't need an explicit return. Simply reaching the end of the function will properly return.
It is no different for void functions that are also recursive. The first return in your function is required because you want it to return before reaching the end of the function, but the second isn't required.
A function returning void doesn't have to explicitly return. A program has 1 entry point, but might have multiple exit points. Consider the following example:
void print(int var)
{
if (var)
return; // first exit point
/*
* do stuff
*/
// second exit point
}
It has 2 exit points. Second one is without a return;.
try this :
#include <stdio.h>
void func (int num)
{
if (!num){
printf("0\n");//print 0 before you stop
return;
}
func (num-1);
printf ("%d\n", num);
}
int main ()
{
func (10);
return 0;
}

Recursive function in C (to print a piramid of #)

I´m following the famous course cs50.
During a class, the teacher showed a program that printed out a pyramid of a height given as an input from the user:
#include <cs50.h>
#include <stdio.h>
void pyramid(int n);
int main (void)
{
int height = get_int("height:");
pyramid(height);
return 0;
}
void pyramid(int n)
{
if (n==0)
{
return;
}
pyramid(n-1);
for (int i=0; i<n;i++)
{
printf("#");
}
printf("\n");
}
Can please someone explain me, what the recursive function pyramid does?
I debug it and I see that given the input is checking if it is equalto 0, then it calls itself until n==0 and returns. After that the debugger goes to the loop for and does it n time.
Following a liner path, it is not supposed to go to the for loop.
Why it does it?
Thank you very much for your help!
After some value of height is set, then a function piramid is called. If the value of height is 0, then the function finishes. Otherwise it calls itself with decreased argument height, which allows you to print each level of the pyramide. As you can see in the body of void piramid(int n), it calls itself first, then prints n "blocks".
Let's say we are working with height = n and try to analyze what happens (each dot is another step):
piramid(n) calls:
piramid(n-1) calls:
piramid(n-2) calls:
...
piramid(1) calls:
piramid(0) - that returns nothing, it is the last recursive call of piramid, so we start going back: in our case it means we print hashes in the order from top to bottom:
# is printed, as piramid(1) is on top of the stack and after we print it, then we pop it, so piramid(2) becomes the first element on top
## are printed, piramid(2) is on top of the stack, we pop it and continue working with other calls the same way,
...
(n-1) # are printed, we pop it from the stack,
n # are printed, our stack is now empty.
To make it understandable, let's take an example with a small number :
#include <stdio.h>
void piramid (int n);
int
main (void)
{
piramid (2);
}
void
piramid (int n)
{
if (n == 0)
{
return;
}
piramid (n - 1);
for (int i = 0; i < n; i++)
{
printf ("#");
}
printf ("\n");
}
What it does:
main calls piramid(2)
piramid(2) calls piramid(1) however piramid(2) didn't finish as you stated
piramid(1) calls piramid(0)
piramid(0) does nothing as it returns immediately
piramid(1) finishes and prints #
piramid(2) finishes and prints ##
If n was bigger it would follow this but with more steps
Hope it could help and sorry if my answer isn't great as it's my first try answering on stackoverflow (if you have suggestions of how I should answer don't hesitate to tell me)

what is the working rule of this program, Explanation?

i am little confuse in this program i want if anyone could explain to me the functionality of this code and the output, i am getting the output of this program as such
1
1
2
2
3
3
All i want to know the working rule of that two functions how they calculating the values?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int M(const int n);
int F(const int n)
{
return(n==0)?1:n-M(F(n-1));
}
int M(const int n)
{
return (n==0)?0:n-F(M(n-1));
}
int main()
{
int i;
for(i=0;i<6;i++)
{
printf("%2d\n",F(i));
}
printf("\n");
return 0;
}
Consider on for
for(i=0;i<6;i++)
{
printf("%2d\n",F(i));
}
Short answer:
F(0) => 1;
F(1)=> 1 - M(F(0))
when F(0):1 then F(1) = 1 - M(1)
go to calculate M(1), but we start from 0, M(0)= 0;
M(1) = 1- F(M(0)) = 1- F(0) = 1-1=0;
last we have M(1) = 0; and as F(1) = 1-M(1) = 1-0=1
last we have: F(1)=1
More complete:
Let see F() way of working.
the last command in F(),
return(n==0)?1:n-M(F(n-1));
expanded to
if (n==0){
return 1;
}else{
return n-M(F(n-1));
}
In first for iteration i:0, we want F(0) as n is zero, (n:0), the if (n==0) is true , return 1; is executed and value ofF(0) have to be 1.
for second iteration we want F(1), for that if (n==0) is false and else block is execute.
as now the n:1, F(1) = 1 - M (F(0)).
In previous iteration we have F(0)=1, OK now we can rewire or equation: F(1) = 1 - M(1), it obvious that if we have value of M(1) simply , put it on to the last formula , F(1) have been solved.
for this we must expand M() function.
Similarly we can write for M().
if (n==0){
return 0;
}else{
return n-F(M(n-1));
}
M(0) = 0;
M(1)= 1- F(M(0))= 1- F(0) = 1 - 1=0;
now we have M(1) = 0; by putting it on the F(1) = 1 - M(1)
we achieve to F(1) = 1.
Now the first two pair of 1 in output of your code is calculated by hand.
for others, do this way over and over.
As suggested in the comments try to trace the code by hand, I will go through the first two iterations with you so you get the idea
When your program starts it calls your main function, and starts executing the for loop as follows:
i=0 => calls F(n=0) => is n==0 true? Yes => return 1 => print 1
i=1 => calls F(n=1) => is n==0 true? No => then 1-M(F(0)) => F(0) calculated from the previous iteration to return a value of 1 => call M(n=1) => is n==0 true? No => then 1-F(M(0)) => M(0) returns 0 since n==0 is true => then 1-F(M(0)) is equal to 1-F(0) => we calculated F(0) to return 1 => so 1-F(0) return 0 from M => take the return back to 1-M(F(0)) => 1-0 = 1 => print 1
Do not be frustrated because what you are asking would be actually much easier to understand with some patient. I extremely recommend that you hold down a pen and paper and start tracing yourself.
Go iteration by iteration as I did.
Call each function according to the correct flow of the if conditions.
When you call a function, mark where you have left in the code to jump to said function, such that once it returns a value, you know exactly where to place the returned value.
Peace of paper, patience, and trace.

Resources