Recursion in C programming Language - c

I am learning recursion now-a-days. Here are three codes. The first and third is giving me the expected output but the second is not? Can somebody tell me what is just the difference in them.
Code 1:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(i-1);
}
}
int main()
{
tail(5);
}
Code 2:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(i--);
}
}
int main()
{
tail(5);
}
Code 3:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(--i);
}
}
int main()
{
tail(5);
}
output of Code 1:
5
4
3
2
1
output of Code 2:
5
5
5
.
.
. Infinite
output of Code 3:
5
4
3
2
1
Please help me out. I am confused!

Result is as expected
decrement is post decrement so it would first use current value and then decrement. So function gets repeatedly called with current value so infinite loop.
Working fine for me . Similar to first

Of course code number 2 won't. In code number 2 you typed tail(i--); what -- operator (after the variable name) does is first using him in the line you requested and THEN decrease him by one.
Let's say I have the line printf("%d", i--); It'll print i in it's current value and only after printing it, it will be decreased, it first uses I, and then decreases it - same would happen if you would just type:
printf("%d", i);
i--;
About the -- operator BEFORE the variable. It'll first decrease and then do the requested action - so printf("%d", --i); will decrease i by one and then print it.
We all agree code 1 works well, code 2 actually is in an infinite loop BECAUSE you decrease the variable AFTER calling the function - so it decreases in one function only.
Basically, what it does is like:
printf("%d", i); //which is 5
tail(i);//which is still 5
i--; //will never get to this line because we called another function with variable 5
and so on.
About code number 3, it works perfectly, it's like code number 1 (but code number one won't actually decrease the variable, just call the function with the variable-1).
EDIT:
for more information, you can search in this article :)

The 3 have to work. The 2 don't work because i is decremented after been passed to the function.

You should work with pointers in second case. Each time you are passing the same value into recursive function ... first goes function call and after that you have decrement operation. As a result you have the same value (5) in each recursive call.

The second doesn't give you your desired output because you are using post-decrement operator i--.
This means "use i and then decrement i" as opposed to --i which means "decrement i and then use i".
So in your third case, i whose value is 5, gets decremented to 4, and then tail(4) is called.
In the second case, tail(i--) is called, which means call tail(5) and then do i-=1; .
If i-- and --i are given as standalone statements, they are equivalent, for example
for(int i=5;i>0;i--)
is effectively the same as
for(int i=5;i>0;--i)
But in cases such as follows:
int i=5;
int a=i--;
printf("%d %d", i, a);
This gives out put 4 5 whereas
int i=5;
int a=--i;
printf("%d %d", i, a);
will give output 4 4.

Related

Unexpected answer

I took a C Advanced Course on Udemy, and there is a question from there:
What will be the output of the following code?
#include <stdio.h>
int main(void){
static int i=5;
if(--i){
main();
printf("%d ", i);
}
}
The right answer is 4 3 2 1, but when I run this code in my IDE (and online compilers), it prints 0 0 0 0.
In the course lector uses cygwin compiler and I have g++. May it be the reason of the inconsistency?
Also I'm wondering if if(--i) method is faster then for loop by the concept of performance?
Thank you.
The reason is main() is called before printf("%d ", i). So when if block is executed, main() function is called before printing the value of i and it's continue to do so until if-condition is false. Here if-condition became false when i is equal to 0. When the if-contidion is false the function return to the previous state from where it have been called and then print the value of i, which is now 0.
To print 4 3 2 1, print the values before calling main() funtion like bellow
int main(void){
static int i=5;
if(--i){
printf("%d ", i);
main();
}
}
The posted code shall print 0 0 0 0 because the printf is after the recursive call, i.e.
main(); // Recursive call
printf("%d ", i); // Print after
If you instead do:
printf("%d ", i); // Print before
main(); // Recursive call
the output will be 4 3 2 1
So I think your lector used the last form and you used the first form, i.e. different code, different results

Output is 5 5 6 7 8 9 explain how?

Can someone please explain how this recursion is working in the following code?
#include<stdio.h>
func(int x)
{
if(x>5)
func(--x);
printf("%d",x);
}
int main(void)
{
func(10);
return 0;
}
The function logic works that way:
If x is bigger than 5, the function will be called again with x decremented by 1.
In the following line:
func(--x);
--x means that x will be decremented by 1 before this code line executes, different than x-- which means x will be decremented after the line.
When x will be equal to 5, it will be printed and then the function will return to the last place it was called from and continue from there, meaning x will be printed again with the value it had in the last call, then return again so on and so forth.
So the function will basically print all the numbers from 5 to the given number (if it’s bigger than 5 of course), excluding the given number, since x was decremented before it was printed.
In your case the call func(10) will result in the following output:
56789

Confusion with i++ and i=i+1

Please do help me with explaining the output of my code. Currently I'm an amateur in C. If i++ and i=i+1 are the same things then why such difference in output?
#include <stdio.h>
void main()
{
int i=0;
printf("%d %d %d \n",i++,i,i++);
int j=0;
printf("%d %d %d \n",j=j+1,j,j=j+1);
return 0;
}
output:
1 2 0
2 2 2
Process returned 7 (0x7) execution time : 0.081 s
Press any key to continue.
To understand the logic behind your output, you need to have an idea of Pointer and how it works.
The C language exhibits an undefined behavior (https://en.wikipedia.org/wiki/Undefined_behavior) where you can't predict the way the syntax will work on the execution.
i++ -> increments i, but returns the previous value of i.
++i-> increments i, and returns the new value of i after assignment.
i = i + 1 -> adds 1 to i, writes it to i, and then returns the new value of i after assignment.
Refer this link for more info: https://en.wikipedia.org/wiki/Sequence_point
Based on this principle, the output can be analyzed as below.
int i=0;
printf("%d %d %d \n",i++,i,i++);
Firstly, i=0
it starts execution from the right side i++
First, it assigns the value& the pointer stores 0; then the increment will take place. So, i=1.
In the next step, there is only a variable. So, the pointer doesn't store the value; it only stores the address. Therefore, i=1.
Last step execution is the same as the first step. So, i=2.
Now, it will print the stored value. So, the output is 1 2 0.
Now, let's analyze the second OUTPUT.
In the second output, the expression is j=j+1.
So, first, it executes all the steps and then prints the value.
So, the second output is 2 2 2.
I hope you now got the difference between i++ & i=i+1.

Recurse loop trace

I have written the following code
#include <stdio.h>
void recurse();
int main()
{
recurse();
return 0;
}
void recurse()
{
static int n=987654321;
if(n==0)
return ;
printf("%d",n%10);
n=n/100;
int a=n;
recurse();
if(a!=0)
printf("%d",a%10);
}
I am not understanding why the output is coming 135799753?
What I thought the answer to be was 135799 because after printing the first 9 after 1357 n will become 9 and hence n/100 will be zero so the recurse function will return to the main without printing anything.
Please correct me where I am wrong.
Thanks in advance!!
Output of program is correct. Your output also consists of these values -
if(a!=0)
printf("%d",a%10);
Value of a is also printed if it is not 0. But the values are printed from last to first because of these statements after the recursion call.
You consider output to be 135799. Second 9 being value of a%10 but value of a%10 from previous recursion calls is also to be printed as those statements get executed after the end of recursion call.
You can see in this example.

Misunderstanding in basic for loop (C)

I have been going through some exercises from a recommended book I found on this website. I came across this following basic piece of code, which I could not fully understand.
#include <stdio.h>
int main(void)
{
int i;
for (i = 10; i >= 1; i /= 2)
printf("%d ", i++);
return 0;
}
This is my reasoning behind this program fragment:
Variable i is initialised to 10.
i is tested to see if greater or equal to 1, (which is always the case).
The third expression reads: i = i / 2, thus i is divided by 2 and its value stored in i.
In the printf statement i is incremented after each printf statement.
I simply cannot understand why the output of this program is:
1 1 1 1 1 1 1 1 ...
I get that the condition statement is always true, however shouldn't the first values be:
5 3 2 1 1 1 1 1?
Basically I cannot seem to understand why the value of i is straight away being stored as 1. Any corrections regarding my reasoning and/or insight on the matter will be appreciated. Please do excuse the basic nature of this question.
As #abelenky pointed out, the correct output is 10 5 3 2 1 1 1 .... The only mistake you made in your reasoning is that the statement i /= 2 gets evaluated after the body of the for loop, before testing the condition again. Another way to write the same loop would therefore be
for(i = 10; i >= 1; i = (i + 1) / 2)
printf ("%d ", i);
If you are running on Windows, try paging the output through more: myprog | more. This should allow you to see the beginning of the output of this infinite loop. On a linux machine, you could acheive the same result using more or less: myprog | less. Thanks to #EugeneSh for making the suggestion that this could be the issue.
Another way that I have found to view the initial output for programs like this is to hit Ctrl+C immediately after starting the program with Enter. This is not a "standard" method and may require very quick reflexes to get any results for a quick loop like yours.
A final suggestion is to limit the output you produce from the program directly:
int i, count;
for(i = 10, count = 0; i >= 1 && count < 100; i /= 2, count++)
printf("%d ", i++);
This will add a counter that will stop your output after 100 numbers have been printed and allow you to see the first numbers.
On the second line, you have 'i++'.
Thus at each iteration of the loop, it will also increment i by 1.
So supposing i = 1 when you start the loop. First it will be divided by 2 (i /= 2). Since i is an integer, it will become 0. Then, on the second line, you have 'i++', thus incrementing i.
So by the end of the loop iteration, i will be back to being equal to 1 (thus making this loop infinite).

Resources