Recurse loop trace - c

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.

Related

Need reason for the occurrence of following output

main(){
int a[5]={1,2,3,4,5};
int *ptr=(int *)(&a+1);
printf("%d %d",*(a+1),*(ptr-1));
}
The output of this code is coming out to be : 2 5 .
I understand why 2, but why 5 is coming for *(ptr-1)?
Also ,
main(){
while(1)
{
if(printf("%d",printf("%d")))
break;
else
continue;
}
}
This code is showing the output as : Garbage value . How and why?
printf() function returns an integer. Upon success, the return value is number of character written. And upon error, the return value is negative.
since the printf("%d") (inner one of printf("%d",printf("%d"))) will be executed first, it will most likely show some random value of a memory location. After that printf("%d",printf("%d")) will print number of values written during the previous call.
Example: 123456789010

How do you explain the discrepancy in the output of this piece of code?

This piece of code is giving unexpected output. When I comment printf of sumdig function the return value of a is 6 and b is 12 but when printf is retained a is 5 and b is 6. Please explain.
main()
{
int a,b;
a = sumdig(123);
b = sumdig(123);
printf("\na=%d b=%d",a,b);
return 0;
}
int sumdig(int n)
{
static int s=0;
int d;
if(n!=0)
{
d=n%10;
n=(n-d)/10;
s=s+d;
sumdig(n);
}
else
return s;
printf("\n s=%d",s);
}
If you don't have an explicit return statement an int c function is apt to return whatever value was returned by the last function called (although I believe the actual behavior is undefined). Therefore
you are returning the result of printf when you mean to return the value of the recursive call to sumdig.
Instead of sumdig(n);, try return sumdig(n);
Right, firstly you should compile this with as many warnings as your compiler will give you.
This'd show you that although sumdig returns a value, there's at least one code path that doesn't return anything so the caller will get rubbish.
Secondly you have a static variable that is never re-initialised so every client call will accumulate extra stuff in s.

Getting output from recursion manually in C

So, I have two questions.
Question 1) I find recursion difficult in C. And I have this one question, that I dont know how should I go about attempting it. I want to know its output, Please help me.
#include <stdio.h>
void fun (int);
int main (void)
{
int a;
a = 3;
fun(a);
printf("\n");
return 0;
}
void fun ( int n )
{
if ( n > 0 )
{
fun(--n);
printf("%d",n);
fun(--n);
}
}
How can I solve this recursion manually?
I know during recursion, the information is stored on stack. Therefore, I tried doing it by that way. Firstly, a will be decremented all the way upto 0. But then, it will exit out of the loop. So, when will it print the values?
Question 2) Also, I Wanted to know since the topic I am studying right now is functions. If I make a function and lets suppose it returns some value, then IS IT MANDATORY that I collect its value upon calling or I can call it without collecting its return value?
For eg: Let's say I made the function as,
int foo ( int a )
{
........
return b;
}
Now, if I call this function from inside main, then is it mandatory that I store the returned value in some variable?
You had 2 questions: the first one is what happens in your code:
To your question #1: Function fun(n) could be rewritten so that it is functionally equivalent but easier to understand, as:
void fun(n) {
if (n > 0) {
fun(n - 1);
printf("%d", n - 1);
fun(n - 2);
}
}
That is:
for fun(n)
if n > 0,
first call fun(n - 1)
then print the number n - 1
lastly call fun(n - 2)
Thus the following happens when unwinding the recursion:
fun(3) ->
fun(2) ->
fun(1) ->
fun(0) ->
n <= 0 -> exits
prints 0
fun(-1) ->
n <= 0 - exits
prints 1
fun(0) ->
n <= 0 - exits
prints 2
fun(1) ->
fun(0) ->
exits as n <= 0
prints 0
fun(-1) ->
exits as n <= 0
Execution goes from up to down sequentially - thus the output 0120 from the prints lines.
Question #2:
No, return value does not need to be stored in a variable. In fact, the printf you used returns an int, that tells the number of characters written, but you did not store that return value anywhere.
For no 1 - Get a note pad and a pencil.
Start off an write fun(3) - It is in Main.
You can now cross that out an instead write
if ( 3 > 0 )
{
fun(2);
printf("%d",2);
fun(1);
}
(applying the logic of --n)
Repeat with both of those fun. You can do the leg work on this one
Number 2 - You do not have to collect the return value from a function
I would like to answer your second question About storing the value returned by the called function.
The answer returned by the called function can be displayed in two ways..
No.1-You need not store it in any variable in the calling function and print it directly as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, b=9, add(int,int);
printf("Sum of %d and %d is : %d",a,b,add(a,b));
getch();
}
int add(int m,int n)
{
return(m+n);
}
Here,the function call has been written in the printf() function and hence the need of an extra variable has been eliminated
No.2-The other way and the code for the same-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a=10,b=9,c,add(int,int);
c=add(a,b);
printf("Sum of %d and %d is : %d",a,b,c);
getch();
}
int add(int m,int n)
{
return(m+n);
}
So,you do need a variable for the second method.Because there has to be something to catch the value thrown by the called function

Recursion in C programming Language

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.

Factorial program using recursive function in c with while loop

Factorial program using recursion in C with while loop. Hi all thanks for your valuable replies.
You all said use (if condition Instead of while). Its correct I accept your suggestion. Then why don't I use while for finding the factorial using recursive function.
Somebody said while(n>1) is an infinite loop. But in this program n value is decremented in the fact(n-1) function itself. Now in this program I put a printf() and getch() after the while loop to know the value of n. The printf() and getch() function executes only when the while condition becomes false.
When I run this program the printf() function and getch() function executes repeatedly and the printf() function return n value = 1. So I determine that the value of n is decremented. Then why does this program execute the while loop again and again?
In all function the return statement is the last function termination statement. When the execution reaches the return statement the execution terminate from the function and go back to the next line of the called function.But in this program after the execution reaches the return statement it will repeat the same function to execute. Why is that?
Note: I am using Turbo C 3.0 to run this program,
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x=n*fact(n-1);
}
printf("N value after the while loop:%d",n);
getch();
return(x);
}
void main()
{
int n,fact1;
scanf("%d",&n);
fact1=fact(n);
printf("%d",fact1);
}
You do have an infinite loop. The line fact(n-1) doesn't decrease the value of n. It invoked another call of the function with a smaller n.
So, if you call fact(2), you have a call with n==2. In this function, you have an infinite loop that call fact(1). In this second call, n==1, so the loop condition is false, and this call prints your line and return - into the infinite loop of the first call (which its n is still 2).
First of all may I suggest you put a prompt like that before scanf? It is strange to be prompted for a number by the console when there is no text asking you to do so. Looks like the program has hung.
printf("Give the value of n:");
So in order to fix your program I would suggest you do something like the example below.
You have to understand how recursion works. You can't just be calculating a number inside the while(). You have to be returning something , else it's an infinite loop.
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x = n*fact(n-1);
return x;
}
return x;
}
void main()
{
int n,fact1;
printf("Please provide the value of \'n\':");
scanf("%d",&n);
fact1=fact(n);
printf("Result is %d",fact1);
return 0;
}
Here i would have a pretty easy code to understand for you. It is very short and effective. Of course i coded it using recursion:
The only header you need to include is stdio.h.
Main:
int main() {
unsigned long n;
scanf("%lu", &n);
printf("%lu\n", factorial(n));
}
Function calculation factorial:
unsigned long factorial(unsigned long n) {
if (n==1) {
return 1;
} else {
return n * factorial(n-1);
}
}
As you see it's a pretty short and effective program. I used unsigned longs, so that the program can output and can calculate with very long numbers without getting overflows or stuff like that. You don't need any kind of loop, just the recursive function.

Resources