I cant understand why my code output is 2,2,3 and also when I remove u++ it's output is 2,5,5 I am using code_block on windows 7 with gcc
I try to dry run my code but its output is different what I calculate
int f(int);
int u = 1;
int main()
{
int n = 3;
//scanf("%d", &n);
f(n);
}
int f(int n)
{
if (n == 0)
{
return 2;
}
else
printf(" %d \n", f(n - 1));
u++;
}
I expected 2,1,0 may be I am wrong but I cant understand why output is 2,2,3 and when I remove u++ it make big confusion for me
In the n != 0 path, your function does not explicitly return a value, and the value returned will be undefined.
It is also not clear to me why you return 2 when n==0 - you do nothing with this value, and it seems arbitrary.
Consider this:
int f( int n )
{
if( n != 0 )
{
n-- ;
printf( " %d \n", n );
n = f( n ) ;
}
return n ;
}
It is both simpler (no else block), and has a single point of exit with an explicitly defined return value.
Let’s trace it through:
You call f(3)
f(3) calls printf("%d", f(2)) - f(2) must be evaluated before printf is called
f(2) calls printf("%d", f(1)) - f(1) must be evaluated before printf is called
f(1) calls printf("%d", f(0)) - f(0) must be evaluated before printf is called
f(0) returns 2
The printf call from step 4 is made with the result of f(0), which is the value 2 - this is the first 2 in the output
u is incremented and now holds 2
f(1) exits without returning a value - you’ve invoked undefined behavior here, and from now on any result is possible. What’s likely happening is that the result of u++ has been stored in the same register used to return values from a function.
The printf call from step 3 is made with the result of f(1), which is undefined.
u++ is incremented and now holds 3.
f(2) exits without returning a value.
The printf call from step 2 is made with result of f(2), which is undefined. Again, what’s likely happening is that the result of u++ has been stored in the same register used to return values from a function.
This is why you saw a different result when you took out the u++ statement.
Note - I say this is a likely explanation based on real behavior I have observed in the past; however, the key property of undefined behavior is that it is undefined - it doesn’t have to be consistent or repeatable. The output could vary from run to run without rebuilding the code. It’s possible that you’re seeing that output for a completely different reason. The key takeaway is that there is an error in your code (not returning a value from f when n > 0) that needs to be fixed.
The question is, what is f() supposed to return when n > 0? Once you figure that out, add an explicit return for that value. For example, if f() is supposed to return n, then you want something like
int f( int n )
{
if ( n == 0 )
{
return 2;
}
/**
* Don’t really need an "else" here
*/
printf( " %d\n", f( n - 1 ));
u++;
return n;
}
You’ll also want to add a check that n is not less than 0, otherwise your code will recurse until you hit INT_MIN and underflow, and guess what, the behavior on signed integer underflow (and overflow) is also undefined.
Here is the solution:
int f(int);
int main() {
int n;
scanf("%d", &n);
f(n);
}
int f(int n) {
if (n == 0) return 0;
else {
printf(" %d \n", n-1);
f(n - 1);
}
}
You should avoid global variables and there is no need for variable u.
Related
I was learning about recursion in C from https://www.tutorialspoint.com/cprogramming/c_recursion.htm and I tried the number factorial example.
#include <stdio.h>
int fact(int i) {
if (i <= 1) {
return 1;
}
return fact(i - 1);
}
int main() {
int i = 3;
printf("numb = %d", fact(i));
return 0;
}
After I executed the code it printed 1. I reviewed the code and found that I forgot to multiply var i with fact(i - 1) at the end of the function. I fixed it and got the correct factorial, but why is fact(3 - 1) equal to 1?
Edit
I had a very shallow understanding of recursion when i posted this question,i thought fact(i-1) would just execute once and didn't get the meaning of calling the function again in the tutorial and i didn't understand it at first when i read the busybee's answer i think i get it now fact(3-1) called fact(2-1) value of var i is now 1 and it satisfied the if condition and returned 1. Another question in the correct version where i multiply var i with fact(i-1) when i change return 1 to return 2 why does it return 12, from the pattern of return 1 and return 2 it seem to multiply 6 result of the function fact with the number in return why? i admit i did no research on what return does and just kinda went with the flow.
To compute the factorial recursively, i must be a positive integer. So that either the value of i is 0 or 1 the factorial will be 1.
If not, then call the recursive factorial algorithm with (i - 1) then multiply the result by i and return that value as shown:
#include <stdio.h>
int fact(int i)
{
if (i ==1)
return 1;
return fact(i - 1) * i; // You forgot to multiply i here
}
int main(void)
{
int i = 3;
printf("Number = %d", fact(i)); // Displaying the factorial of 3
return 0;
}
fact(3 - 1) returns 1 in your first and erroneous version, because it called fact() with i with 2.
This is not less or equal to 1, so fact() is called with 2 - 1. Now this is less or equal to 1, and 1 is returned.
This result is unchanged returned again, and finally once more returned to main().
As a list:
main() calls fact(3).
fact(3) calls fact(2), because its i is 3 and so greater than 1.
fact(2) calls fact(1), because its i is 2 and so greater than 1.
fact(1) returns 1 to fact(2), because its i is less or equal to 1.
fact(2) returns the 1 returned from fact(1) unchanged to fact(3).
fact(3) returns the 1 returned from fact(2) unchanged to main().
main() prints the 1 returned from fact(3).
Edit:
When you're in doubt how your functions are called and what they do, use a debugger (best approach) or insert some printf() (poor man's debugging, but quite easy), like this:
int fact(int i) {
printf("fact(%d) begins ...\n", i);
if (i <= 1) {
printf("... fact(%d) returns 1 because of %d <= 1\n", i, i);
return 1;
}
#if 1 // just temporarily
printf("... fact(%d) calls fact(%d)\n", i, i - 1);
int r = fact(i - 1);
printf("... fact(%d) returns %d\n", i, r);
return r;
#else
return fact(i - 1);
#endif
}
Edit 2:
You might have missed some important things in the lesson on recursive functions.
Each function has its own set of parameters and local variables.
In general, a recursively called function does not have any insight in the local variables or parameters of the calling function.
A recursively called function returns to the calling function. (Some compilers might optimize a "tail call" into a "tail jump", though.)
Forewarning, this is a homework assignment.
I am supposed to create a recursive function but I am doing this wrong. When I enter a 4 I am supposed to get a result of 16 from f(x) but I get -2. I don't really understand where I went wrong. Also I don't know if I am supposed to print my results inside of main or in f.
Write a program that queries the user for an integer value and uses a recursive
function that returns the value of the following recursive definition:
f(x) =x+3 if x <=0
f(x)=f(x-3)+(x+5) otherwise
My attempt:
#include <stdio.h>
int f(int x); //Prototype to call to f
int main(void) {
int n; //number the user will input
//Ask user to input data an reads it
printf("Enter a whole number: ");
scanf("%d", &n);
//Pointer for f
f(n);
//Prints results
printf("\nn is %d\n", n);
printf("f(x) is %d\n", f(n));
return 0;
}
int f(int x) {
//Checks if equal to zero
if (x <= 0) {
x + 3;
}
//If not equal to zero then do this
else {
f(x - 3) + (x + 5);
}
}
Thank you all for the help, learned a lot from your comments and suggestions.
I was able to get it work I believe https://pastebin.com/v9cZHvy0
as far as I can see first one is scanf
scanf("%d", &n);
second one is your function f is not returning anything, so this
int f(int x) {
//Checks if equal to zero
if (x <= 0)
{
return (x + 3);
}
return ( f(x-3) + (x+5) );
}
minor - the below statement is actually useless
//Pointer for f
f(n);
As a student of life, I am always willing to help a fellow academic:
Your code has a few errors that should be of note:
int f(int x) has no return statement, even though it is expecting an integer. I assume you wish to return the result of the program (See Issue #3).
You execute f(n) twice. First on line 12, then again on line 16. printf("f(x) is %d\n", f(n)); actually executes F(n) in order to receive its return value to associate with the %d format specifier.
You have not assigned x+3 OR f(x-3) + (x+5) to any integer. These statements do not save the return values of f(x) that you need to return.
This link may be of help to you:
https://www.geeksforgeeks.org/c-function-argument-return-values/
Notice specifically how the output of functions are captured.
Hope this helps (And I wish you academic success!)
can somebody explain to me how did we get this output?
OUTPUT:
Q
B C D
This is my code:
#include <stdio.h>
char x = 'A';
void fun_1(int n) {
if(n>0) fun_1(n-3);
if(n == 0 ) printf("Q\n");
printf("%c ", ++x);
};
int main()
{
fun_1(6);
return 0;
}
You have a recursive function, recursive means that at some point it calls
itself. The terminal case (when the function stops calling itself) is when n == 0.
When dealing with recursive functions, you have to think this way:
Recursion level 0 (the first call)
n == 6 ==> if(n>0) fun_1(n-3); is executed
Recursion level 1
n == 3 ==> if(n>0) fun_1(n-3); is executed
Recursion level 2
n == 0 ==>
if(n == 0 ) printf("Q\n"); is executed, output is "Q\n"
printf("%c ", ++x); is executed, x is now B, output is B
this is terminal case, therefore
(back to)
Recursion level 1
printf("%c ", ++x); is executed, x is now C, output is C
(back to)
Recursion level 0
printf("%c ", ++x); is executed, x is now D, output is D
Now the recursive calls have ended and you are back in main. As you can see
from the analysis of the recursion levels, the generated output is
Q
B C D
Here's the calls that would be made:
fun_1(n=6)//from main
fun_1(n=3)//since 6 > 0 {
fun_1(n=0){//now n is not greater than zero, so don't recurse
execute if n == 0, yes it is, so output Q
print ++x, x was A now after ++x, x would be 'B'
}
since n <> 0, don't output Q
print ++x, x was B, so print C which is after pre-incrementing x
}
since n <> 0, don't output Q
print ++x, x was C, so print D which is after pre-incrementing x
}
Guys can somebody explain to me how did we get this output?
I'm able to reproduce:
% vi aaaa.c
[ code copied in the editor ]
% gcc aaaa.c
% ./a.out
Q
B C D
I hope that helped!
(that was a joke, if it's not clear to everyone...)
You can try to add a printf in the function fun_1. You see that it's called recursively 3 times with the values 6, 3 and 0.
The last call will print the Q then the B. Then the second call will print the C and the first one the D.
void fun_1(int n) {
if(n>0) fun_1(n-3);
if(n == 0 ) printf("Q\n");
printf("%c ", ++x);
};
with the first call of this method in the main function, you send the value of 6.
if(n>0) fun_1(n-3) with this statement, because 6>0, recursive process is started and 6-3=3 is sent back to fun-1 function. But here, the most important thing to keep in mind that, the first function which is created in memory is not terminated. For each recursive step, there will be created new functions for new n values. So here;
printf("%c ", ++x);
this statement will be working with the same number of recursive loop. Because you used, pre-incrementation as "++x", the char value x = 'A' will first be incremented and then printed. So for every recursive loop step, all the functions which are created are terminated by a sequence of creation, and they printed the pre-incremented value as in output.
I am studying how to program and have recently been working on a problem that calculates the total of 2 entered numbers from min to max. For example, if someone entered the numbers 4, 7. The calculation would be 4+5+6+7=22.
I've attempted what i think would be the definition of recSum but obviously it is wrong as I get a segmentation fault. What is wrong with my definition?
/* Define the recursive function */
int recSum (int x, int max)
{
int incrementalSum = 0;
if (x == max)
{
return x; /* Exit if summated lower to upper numbers */
}
else
{
return (x + recSum(x++, max)); /* My recursive call */
}
} /* End of function call */
*new code is shown above, sorry, i used the wrong code.
Your code has 3 important problems
The expression
incrementalSum = x + x++;
is undefined, read this for more information
Your function is not recursive, a recursive function calls it self until a condition happens where it should end.
Also, noting that I am not an irrational "don't ever use goto person", this is precisely why some people advice against using goto.
The reason your code doesn't work is this line:
return x + recSum(x++, max);
x++ increments x but returns the previous value, so in the recursive calls it never increments and you never reach the base case. Like an infinite loop. You have to replace x++ with ++x in order to give any result, even though it won't be correct. ++x is modifying x so it will alter the final sum of x + recSum. You'd better use:
return x + recSum(x + 1, max);
See What is the difference between ++i and i++?
It seems you mean the following
int recSum(int x, int max)
{
return max < x ? 0 : x + recSum( x + 1, max );
}
Or it would be even better to declare the return type of the function like long long int.
long long int recSum(int x, int max)
{
return max < x ? 0 : x + recSum( x + 1, max );
}
The function can be called like
printf( "%lld\n", recSum( 4, 7 ) );
As for your function then it exits in the first call
int recSum(int x, int max)
{
int incrementalSum = 0;
recCall: if (x < max)
return incrementalSum;
^^^^^^^^^^^^^^^^^^^^^
because usually it is called when x is less than max. So the function does not make sense. Moreover the function is not recursive because it does not call itself.
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