Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I got this code as an exercise in my school:
#include <stdio.h>
main()
{
int unknown(int a, int b)
{
if (b == 1)
return a;
else
return a + unknown(a, b - 1);
}
printf("Value = %i", unknown(3, 4));
}
The outcome is "Value=12". I can't seem to understand why.
AFAIK it should be a=3, b=4 and then 3+4, right?
The key to this is that unless b==1, unknown() calls unknown() - this is called recursion.
For brevity, I'm going to call the function f instead of unknown:
Some languages present functions like this in a clearer way with pattern matching; the equivalent in an imaginary pattern matching language might be:
f(x,1) := x
f(x,y) := x + f(x,y-1)
And so...
f(3,4) = 3 + f(3, 4-1)
= 3 + f(3, 3)
= 3 + ( 3 + f(3, 3-1))
= 3 + ( 3 + f(3, 2))
= 3 + ( 3 + ( 3 + f(3, 2 - 1)))
= 3 + ( 3 + ( 3 + f(3, 1)))
= 3 + ( 3 + ( 3 + (3)))
= 12
I guess your homework is to decide what a better name for the function is than "unknown". Once you've decided, note that recursion is not the best way to implement that function unless your language has specific support for a feature called tail recursion optimisation (this might be a topic you want to shelve for later).
Also, others have noted that nested functions are not allowed in C -- even though your particular compiler might handle them. That means that although your program does this:
int function1() {
int function2(int x) {
...
}
int x = function2(3);
}
... a standard C compiler would not allow it. The normal way is:
int function1() {
int x = function2(3);
}
int function2(int x) {
...
}
Each time a is added to a for b times
a = 3
b = 4
So, four times a gets added which means 4 * 3 = 12
Edit: a added to a, b times. -Dabo
Its the multiplication using recursive addition . Output should be 12. Finally function will return to main
3 + 3 + 3 + 3 = 12
Note: Although you used nested function here and its working, but it is not allowed by C standard. Its a compiler extension.
Related
i expect the output (or value of silly) to be 36. but what i get is 14. this is fixed when i add parentheses: #define THING (4+2).
but i still want to know what is happening when there are no parentheses and why im getting an output of 14
.
the following is my code:
#include <stdio.h>
#include <stdlib.h>
#define THING 4+2
int main(void)
{
int silly = THING * THING;
printf("%d", silly);
return EXIT_SUCCESS;
}
THING*THING = 4+2*4+2 = 4+(2*4)+2 // because of higher precedence of * than +
= 4+8+2 = 14.
Do remember that MACROs are exactly replaced(substituted) into the code.
The macro is literally inserted in place of THING.
THING * THING is 4+2 * 4+2 is 4 + (2 * 4) + 2 which is 14.
If you want the result to be 36 than you need to define your macro wrapped in parenthesis:
#define THING (4 + 2)
Because macros are (almost) the same as text replacement. int silly = THING * THING; is converted by the preprocessor to int silly = 4+2 * 4+2;, and order of operations means that's processed as 4 + (2 * 4) + 2, not (4 + 2) * (4+ 2).
You need parentheses because order of operations is interfering. Macros just replace text, and so without parentheses, the operations are not being evaluated in the order expected.
THING * THING ----> 4 + 2 * 4 + 2 = 14
So, once you use parentheses, this fixes it because it becomes:
THING * THING ----> (4 + 2) * (4 + 2) = 36
This is explained in this preprocessor tutorial.
I'm trying to write a recursive function in C to take the value of 3 to the power of another number. For example, if I enter 4, the program will return the value 81. And the following code is the answer for the question. But I can not clearly understand how the code can solve the problem. I mean that when 4 is passed to the function, the first 3 lines in the function body will be ignored, jump straight into the " // This line " . Then how is it from there will the program return the number 81. The function calls itself again with 3 passed? 3*three_power(3) ? I can not clearly understand that. Can someone explain? Sorry because it's a stupid question, I'm new to C.
#include <stdio.h>
int three_power(int power);
int main(){
int a=4;
int b=9;
printf("\n3 to the power of %d is %d", a, three_power(a));
printf("\n3 to the power of %d is %d", b, three_power(b));
return 0;
}
int three_power(int power){
if (power < 1){
return( 1 );
} else
return (3* three_power(power-1)); //This line
}
Yes, it takes the else branch on the first way through, which causes the recursive call for 4 - 1 which again takes the else branch, and so on down to the base case when power is 0 which just returns 1 (since 30 is 1).
The full chain is
3 * three_power(3) =
3 * (3 * three_power(2)) =
3 * (3 * (3 * three_power(1)) =
3 * (3 * (3 * (3 * three_power(0))) =
3 * (3 * (3 * (3 * (1)))) =
3 * 3 * 3 * 3 = 81
It's hard to visualize, but that's it.
You can of course single-step through this in a debugger to get a feeling for it, or just add a printf("power=%d\n", power); to the first line of three_power().
This is the essence of recursion.
In a mathematical sense, you can define the power of 3^n as 3 * 3^(n - 1), right? After all 3 to the anything is 3 multiplied times itself that number of times, right?
The recursion simply says that the answer to "What is 3 to the power?" Well it is 3 times three_power of power minus one. You need only handle the case when power is 0 and the returned value will be multiplied times 3 by the number of recursive calls made.
This is an excellent learning exercise, but you should prefer pow(3, power) because it is more efficient to calculate this way and you don't risk to exceed the maximum recursive call stack.
Consider writing the command flow showing each entry and exit for your example. Also the return on the else is a single line else. I will rewrite it showing the correct brackets.
1e. enter with value 4
2e. enter with value 3
3e. enter with value 2
4e. enter with value 1
5e. enter with value 0
5r. return 1
4r. return 3*5r = 3*1 = 3
3r. return 3*4r = 3*3 = 9
2r. retrun 3*3r = 3*9 = 27
1r. return 3*2r = 3*27 = 81
int three_power(int power)
{
if (power < 1)
{
return( 1 );
}
else
{
return (3* three_power(power-1)); //This line
}
}
Another way of putting it with a single return is
int three_power(int power)
{
int rtnval;
if (power < 1)
{
rtnval = 1;
}
else
{
rtnval = 3* three_power(power-1); //This line
}
return rtnval;
}
This is an example of recursion, which is similar to the mathematical concept of induction. For a given input, is invokes itself on a reduced input, then uses that result to produce the desired result.
A good way to understand how the function works is to start with the simplest case, verify that it works, then move on to the next simplest case, etc.
In this example, the simplest case is when power is 0. In that case, it immediately returns 1. So far so good.
Now consider what happens when power is 1. In this case, it returns 3 * power(0). In other words, it calls itself with a different input, then uses that result to produce a new result. We have already verified that power(0) returns 1. So in this case, it will return 3 * 1, which is just 3. Again, so far so good.
So what happens when power is 2? Well, it returns 3 * power(1). This results in multiple nested calls. We know that power(1) will return 3, so this case will return 9. Again, it's doing what we want.
More generally, when power is >= 1, it recursively calls itself to obtain the result for power - 1. This will in general result in a chain of calls which eventually return the desired result for power - 1. It then multiplies this by 3 and returns the result. This is 3 * (3 ** (power - 1)), which is just 3 ** power as desired.
You can confirm its correctness inductively. The basis case is when power is 0. This case is confirmed directly. Then, assuming it gives the correct result for power - 1, we can see that it will also give the correct result for power, from the recursive step. It will only fail if the result becomes large enough to overflow.
I would propose a more efficient recursion than f(n)=3*f(n-1).
It would be
// f(n) = 1 if n = 0
// f(n) = f(n/2)^2` if n is even
// f(n) = 3*f(n/2)^2 if n is odd
int power3(int n)
{
int m;
if (n == 0)
return 1;
else if (n % 2 == 0)
{
m = power3(n/2);
return m*m;
}
else
{
m = power3(n/2);
return 3*m*m;
}
}
This way the time complexity is reducing from O(n) to O(log(n)).
This question already has answers here:
Undefined behavior and sequence points
(5 answers)
Closed 8 years ago.
This is a recursive function I wrote that can compute the ways of coin change, and it can work perfectly.
int cc(int n, int k)
{
if (n < 0 || k == 0)
return 0;
else if (n == 0)
return 1;
else
{
/*** WAY 1 : START ***/
s.stk[++s.top] = k;
int tmp = cc(n - d[k - 1], k);
s.top--;
return tmp + cc(n, k - 1);
/*** WAY 1 : END ***/
}
}
But, why it starts getting wrong answers if I change the code between two comments as follows:
/*** WAY 2 ***/
return (s.stk[++s.top] = k, cc(n - d[k - 1], k)) + (s.top--, cc(n, k - 1));
// |<----- A ----->| |<----- B ----->|
Aren't they equivalent?
P.S. Though it is not a good way to write like that (way 2), I just wonder why it can't work.
EDIT:
Though we don't know that whether A or B will do first, I tried to do some experiments.
The conclusion is that neither return A+B; nor return B+A; will get correct answers.
Read the "Undefined Behavior and Sequence Points" link given by #delnan for details. But the simplest explanation is that there is no sequence point between A + B. As such there is no guarantee as to which one of A and B would be evaluated first. That's why way 1 and way 2 are not equivalent.
In your case:
A = (s.stk[++s.top] = k, cc(n - d[k - 1], k))
B = (s.top--, cc(n, k - 1))
Now, the recursive calls to cc() will occur randomly, sometimes (decided at compile time not at runtime) on path A and sometimes on path B. As such, the order of calls is all screwed up.
You might want to add a print statement at the top of the function that would print the sequence number and the arguments on a new line. Then execute it with way 1 and way 2 using the same initial data. Collect the output in to two text files. Diff these two files and see for yourself where things go wrong.
I was into C today and I bumped into this example of using recursive calls and I don't understand how it works. Can someone explain?
#include <stdio.h>
#define SIZE 10
int sample(const int b[], int p); //function prototype
void main(void){
int x;
int a[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
x = sample(a, SIZE); //call
printf("Result is X: %d\n", x);
}
int sample(const int b[], int p){
if (p == 1){
return b[0];
}
else{
return b[p - 1] + sample(b, p - 1); //recursive calls until p is 1
}
}
My question is: Why the output is 55? Does x save the previous value and then add next from next call of the sample? Why the value of x is not just b[0] which is 1?
What might help is to write out a table of the value of p at the first call of sample:
p b[p - 1]
-------- --------
SIZE 10
Since p is not 1, the function sample returns the calculation:
b[SIZE - 1] + sample(b, SIZE - 1)
Or:
10 + sample(b, SIZE - 1)
To calculate sample(b, SIZE - 1), we write out the next value in the table:
p b[p - 1]
-------- --------
SIZE - 1 9
Again, p is not 1, so we ultimately return the following value:
(10 + (9 + sample (b, (SIZE - 1) - 1)))
If you repeat these steps, you can see how this eventually terminates, because we get to a state where p is 1:
(10 + (9 + (8 + ... + (1)))
This results in the answer 55.
The answer is 55 as that's the sum of all 10 terms.
What it's doing is summing the last term with the sum of the others. When presented with the first term it returns that, ending recursion and popping the whole stack.
It happen because when you execute the above code then a memory stack of recursive function call outputs is formed till there is a controlling condition like in this case we have
if (p == 1){
return b[0];
}
so the values you get at every level of recursion are as follows
10 9 8 7 6 5 4 3 2 1
Adding all of them you get 55.
The value of x is not just 1 because the return value of each recursive function calls for decremented values of P is added to calculate the return value of previous call at each call till it reaches 1 (the condition in the parent call).
ie return b[p - 1] + sample(b, p - 1);
For brief explanation refer : http://www.programiz.com/c-programming/c-recursion
This question already has answers here:
C macros and use of arguments in parentheses
(2 answers)
Closed 4 years ago.
I am new to c language. I just wanted to know why is my macro not working properly. It is giving me output as 13 where as my expected output is 24.?
#include<stdio.h>
#define mult(a,b) a*b
int main()
{
int x=4,y=5;
printf("%d",mult(x+2,y-1));
return 0;
}
mult(x+2,y-1) expands to x +2 * y -1 that is equals to 4 + 2 * 5 -1 gives output: 13.
You might be expecting answer (4 + 2) * (5 -1) = 6 * 4 = 24. To make it expand like this you should write parenthesize macro as #H2Co3 also suggesting:
#define mult(a,b) ((a)*(b))
Read aslo: So, what's wrong with using macros? by Bjarne Stroustrup.
This is because C macros are simple textual substitutions, the macro writer must be sure to insert parentheses around every macro variable when it is substituted, and around the macro expansion itself, to prevent the resulting expansion from taking on new meanings.
If you observe your program: mult(a, b) is defined as a * b
mult(x + 2, y - 1) = x + 2 * y - 1 = 4 + 2 * 5 - 1 = 4 + 10 - 1 = 13
The Correct way would be:
mult(a, b) ((a) * (b))
Use parentheses in the macro definition
#include<stdio.h>
#define mult(a,b) ((a)*(b))
int main()
{
int x=4,y=5;
printf("%d",mult(x+2,y-1));
return 0;
}
This is because different arithmetic operators have different precedence levels. Hence always use parentheses while defining the macro.
Because it replaces the arguments literally:
mult(x+2,y-1) --> mult(4+2,5-1) --> 4 + 2*5 - 1 --> 13
Try changing the define to:
#define mult(a,b) (a)*(b)
In this case the result after pre-processing is this:
int main()
{
int x=4,y=5;
printf("%d",(x+2)*(y-1));
return 0;
}
This will solve the problem but it's still not the best way to do it.
#define mult(a,b) ((a)*(b))
This version is considered as good practice because in other types of situation the first one would fail. See the bellow example:
#include<stdio.h>
#define add(a,b) (a)+(b)
int main()
{
int x=4,y=5;
printf("%d",add(x+2,y-1)*add(x+2,y-1));
return 0;
}
In this case it would give an incorrect answer because it is translated by the pre-processor to the fallowing:
int main()
{
int x=4,y=5;
printf("%d",(x+2)+(y-1)*(x+2)+(y-1));
return 0;
}
printing 34 instead of 100.
For the ((a)+(b)) version it would translate to:
int main()
{
int x=4,y=5;
printf("%d",((x+2)+(y-1))*((x+2)+(y-1)));
return 0;
}
giving a correct answer.