How to approach this kind of recursion program - c

The answer of simple recursion problem is easy to predict but when it involves multiple calls at a time then it gets difficult (here e(--n) is called two times
in single block of scope).
My problem is how to solve this kind of programs by creating TREE kind of structure
void e(int);
int main(void)
{
int a = 3;
e(a);
putchar('\n');
return 0;
}
void e(int n)
{
if (n > 0)
{
e(--n);
printf("%d ", n);
e(--n);
}
}

If you do it on a piece of paper with a pencil you should get this:
call => e(3);
call => e(2);
call => e(1);
call => e(0);
initial printf: 0
call => e(-1);
initial printf: 1
call => e(0);
initial printf: 2
call => e(1);
call => e(0);
initial printf: 0
call => e(-1);

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 to print "0" and "1" alternatively with only 1 call to printf

This will print alternately "0" and "1":
while(1){
printf("%d", 0);
sleep(1);
printf("%d", 1);
sleep(1);
}
To reduce the calls to printf() down to only 1 time for each loop, I use XOR:
int toggle = 0;
while(1){
printf("%d", toggle^=1);
sleep(1);
}
I would like to know if there are any other ways to print alternately between 0 and 1 (means toggling the output) with only 1 call to printf() (or any other C standard functions) for each loop. And can this achievable without using any variable?
(user-defined function may not be used)
2 easy options at least:
toggle= !toggle;
toggle = 1 - toggle;
and for fun and games that you might not know
toggle = !!!toggle;
toggle = !!!!!!!!!!!!!!!!!!!!!toggle;
And can this achievable without using any variable?
Strictly speaking you obviously need something to store the state of your toggle. However, it doesn’t need to be a variable.
One alternative would be the use of two functions that recursively call each other:
void print_and_wait(int n) {
printf("%d", n);
sleep(1);
}
void print_zero(void);
void print_one(void) {
print_and_wait(1);
print_zero();
}
void print_zero(void) {
print_and_wait(0);
print_one();
}
int main(void) {
print_zero();
}
… but this might violate your “only one call to printf” rule, and strictly speaking it also uses a variable (the parameter to print_and_wait). But it should be clear that you’ll always either need two calls or a variable, since otherwise what do you pass to printf?

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;
}

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.

Stack implemented as an array defaulting first value to 0 in C

I have an assignment where I am supposed to use this very very simple (or so I thought) stack that my teacher wrote in C, just using an array. From this, I have to implement reverse polish notation from a text file.
In order for me to implement this, I am using a stack, pushing values on until I hit an operation. I then do the operation and push the result back onto the stack until the user hits p to print the value.
The problem is, for some reason, my professor's implementation of the stack array defaults the first (index 0) value to 0. Printing the stack without pushing anything onto it should result in null but it appears the output is 0.
Here is my professor's implementation of the stack:
#define STK_MAX 1024
#define ELE int
ELE _stk[STK_MAX];
int _top = 0;
void stk_error(char *msg)
{
fprintf(stderr, "Error: %s\n", msg);
exit(-1);
}
int stk_is_full()
{
return _top >= STK_MAX;
}
int stk_is_empty()
{
return _top == 0;
}
void stk_push(ELE v)
{
if ( stk_is_full() )
stk_error("Push on full stack");
_stk[_top++] = v;
}
ELE stk_pop()
{
if ( stk_is_empty() )
stk_error("pop on empty stack");
return _stk[--_top];
}
void print()
{
for(int i = 0; i <= _top; ++i)
printf("%d ", _stk[i]);
printf("\n");
}
I realize that the print statement will print a value that has not been pushed yet, but the problem is, is that when I don't print it, it still ends up there and it ends up screwing up my rpn calculator. Here is what happens when I do this:
// input
stk_push(2);
print();
stk_push(4);
print();
// output
2 0
2 4 0
How do I get rid of the 0 value that is affecting my calculator? Doing stk_pop() after the pushing the first value onto the stack didn't seem to work, and checking that top == 0, then directly inserting that element before incrementing _top didn't work.
When you are printing, loop from 0 to (_top - 1), since your top most element is actually at _top - 1. Hint : Look at your pop/push method.
void print()
{
for(int i = 0; i < _top; ++i)
printf("%d ", _stk[i]);
printf("\n");
}
"The problem is, is that the rpn calculator relies on the TOS being accurate. When I do pop() though, it will pop 0 and not the real TOS."
Sounds like a problem with your calculator implementation. You assumed the top of the stack would be null, but that's not the case for your professors stack implementation. Simply a invalid assumption.
Instead he's provided a stk_is_empty() method to help determine when you've pop everything.
If you need to pop all elements, you'll need to break on the condition of stk_is_empty().
stk_push(2);
stk_push(4);
while( stk_is_empty() == false)
{
stk_pop();
}
Of course in reality you'd be setting the pop return to a variable and doing something with it. The key point is leveraging stk_is_empty().
I haven't written C++ in few years so hopefully I didn't make a minor syntax error.

Resources