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
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.)
There is this Mario problem in the CS50 course and it's easy using the recursion method, except that when I try to add any arithmetic operation it shows (invalid operands to binary expression ('void' and 'int')). It's just for the sake of me to understand what I can do using recursion and what I can't; the problem is this line (sum(n-1)+n;)
Here is the code:
#include <cs50.h>
#include <stdio.h>
void sum(int n);
int main ()
{
int u = get_int("f");
sum (u);
}
void sum(int n)
{
if (n==0)
{
return;
}
sum(n-1)+n;
for(int i = 0 ; i < n; i++)
{
printf( "#");
}
printf("\n");
}
The error you are seeing is from this line:
sum(n-1)+n;
sum is a function that returns void, but you are trying to add it with an integer n.
I am not quite sure what that get_int("f") does, but I assume it's prompting to the user for an int input, and you are trying to sum from 0 to that number. Here is the solution:
int sum(int n) // Here is the critical change to your code, now it returns an int
{
if (n == 1) // Root case that will stop the recursion, otherwise, it's endless
return 1; // 1 = 1 + 0;
return sum(n-1) + n; // Recursion
}
Think about what we are trying to achieve here. We want to add from 0 to n, or to say from n to 0 downwards. If n is 3, it's going to be 3+2+1+0, and you'll notice that 3 is just n, and 2 is n - 1, 1 is (n - 1) - 1, etc. To visualize it:
before sum(3) could return anything, it calls sum(2) + 3;
before sum(2) could return anything, it calls sum(1) + 2;
1 is our root case, and there is no more calls, so sum(1) is going to return 1;
that 1 is returned to step 2, so sum(1) + 2 becomes 1 + 2, which is 3, and that is the value sum(2), and it returns its result to step 1, and step 1 becomes 3 + 3, which is 6, and the initial call to sum is then completed.
I hope that makes sense to you. Recursion is not an easy technique to master. Take your time, but you need to understand how function calls work in memory. Here is a video that illustrates how recursive calls in memory look like, Data Structures Using C++: Illustration of Recursive Function Calls (Call Stack).
It is because the return type of the function sum() is void.
You cannot add anything to void.
Anyway the result of the "addition" is thrown away, so you won't need addition.
This mean that sum ( n-1)+n; should be replaced with sum ( n-1);.
Can some one explain the execution of this program .
OUTPUT is:
1
2
3
4
3
2
1
how does function retain value 3,2,1 in the end
main(){
int h=0;
g(h);
}
g(int n){
n++;
printf("%d\n",n);
if (n ==4)return 88;
g(n);
printf("%d\n",n);
}
You are getting the above output because at the 8th line of your code you are calling the function agian recursively so the remaining code after the 8th line is saved in the call stack in your memory. So, when you get the output 1 2 3 4, the remaining code that is left (in call stack) is executed hence you are getting this output.
below is the call stack of your program
when n = 0 the stack will place 1
|___|
|___|
|_1_|
when n = 1 the stack will place 2
|___|
|_2_|
|_1_|
when n = 2 the stack will place 3
|_3_|
|_2_|
|_1_|
when n = 4 the stack will not place anything as it encounters the return statement
now, we have some values in our stack
so the program starts popping the top most value in stack (here n = 3) and continue the execution where it left off (i.e it will print the value) and this process will go on until the stack is empty.
NOTE: You can visit this video to understand more effectively about recursion https://www.youtube.com/watch?v=Mv9NEXX1VHc
g(int n){
n++;
printf("%d\n",n); // n=1 print 1 & call g(n) with 1 now g(1) make its own n=2 print 2 & call g(2)
//... print 3 & call g(3) becomes 4 print 4 return 88
if (n ==4)return 88;
g(n);
// now after the return we get back to the 3rd call that called g(3)
//so it print 3 at the end 3 ends
//we go back to the one that called g(2) so we print 2 at the end... & same for 1
printf("%d\n",n);
}
You can read above answers they are pretty good, but here is another way to get you head around it. Simplest answer is the same way that caller function retains its value when calling any function. For example if you have:
int main (void) {
int a = 5;
fun1 (a);
}
void fun1 (a) {
fun2 (a);
printf("%d\n", a); // output would be 5
}
void fun2 (int a) {
a+=1;
fun3 (a);
printf("%d\n", a);
}
void fun3 (int a) {
a+=1;
printf("%d\n", a);
}
So fun1 () would print out 5, fun2 () 6 and fun3() 7. Recursion function is similar to above from perspective of caller and called function, instead of calling function with different name it is calling the function with same name, or in other words it is calling itself.
Look at this code:
void recFun (int a) {
if (a > 6)
printf("%d\n", a);
recFun (a + 1);
printf("%d\n");
}
Some people when I was in school would rewrite above to following (on a piece of paper of course this would yell at you if you try to compile it):
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
printf("%d\n");
}
In C the function arguments acts as local variables inside the function. Further C uses call-by-value which means that the value of variable used by the caller as argument is copied to the functions argument variable. Consequently the two variables are completely independent variables.
Consider this code:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int y)
{
y++;
printf("%d ", y);
foo(y);
printf("%d", y);
}
bar(0);
This will output "1 2 1"
Most people find that it's obvious that changes to x will not change y. They are by name two different variables. So no surprise in that.
If we change the code to use the same name for variables - like:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int x)
{
x++;
printf("%d ", x);
foo(x);
printf("%d", x);
}
bar(0);
The output is still "1 2 1"
Simply because the variable x inside foo is another variable than x inside bar. The only relation ship they have is that x inside foo is initialized with a copy of the value of x inside bar. No matter what kind of change you make to x inside foo it will/can not change x inside bar.
Exactly the same goes for the recursion. Each function call creates its own variable n - completely independent of the n variable in previous calls.
Most implementations use a stack for implementing this functionality. Do a search for "stack frame" to get more information. Also see
Explain the concept of a stack frame in a nutshell
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!)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Basically the question i found on internet is: "How we can print the numbers from 1 to 100 without using of loops and conditions?" and in the answer, I got stuck at some lines below marked with bold. Can anyone explain me what is that?
I think that the total code below is written in C as much i've my knowledge.
#include <stdio.h>
#include <stdlib.h>
void foo(int);
void f1(int x)
{
printf ("%d\n", x + 1);
foo (x + 1);
}
void f2(int x) //why we have used this fumction
{}
void (*tab[])(int) = { f1, f2 }; // what is this
void foo(int x)
{
tab[!(x < 100)](x); // what is this
}
int main()
{
foo(0);
return 0;
}
tab is an array of two function pointers.
Since you're not allowed to use if, instead you use an array of functions, and index them using the result of the !(x < 100) comparison. When that's true it evaluates to 1, so you call the function in tab[1], which is f2(). When it's false it evaluates to 0, so you call tab[0], which is f1. So it effectively the same as:
if (x < 100) {
f1(x);
} else {
f2(x);
}
f1(x) prints x+1 and then calls foo(x+1) recursively. f2(x) doesn't do anything, so the recursion ends when you get to this.
void (*tab[])(int) = { f1, f2 }; // what is this would be an array of function pointers which take an int argument.
tab[!(x < 100)](x); // what is this
this means that you are accessing function 0 or 1 depending on the evaluation of the condition (false - 0 or true - 1)
The code seems to be a recursive call which would stop at 100
How about this:
#include <stdio.h>
int p(int n) {
return printf("%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n",
n+1, n+2, n+3, n+4, n+5, n+6, n+7, n+8, n+9, n+10);
}
int main() {
return p(0), p(10), p(20), p(30), p(40), p(50), p(60), p(70), p(80), p(90), 0;
}
Or this more compact version, that prints one number at a time with a non obvious termination test:
#include <stdio.h>
int p(int n) {
return printf("%d\n", n++) - 4 && p(n);
}
int main() {
return p(1);
}
Incidentally, one can make it even more cryptic this way:
#include <stdio.h>
int main(int argc, char *argv[]) {
return printf("%d\n", argc++) - 4 && main(argc, argv);
}
The 2 versions above still use tests, just not if statements.
Here is a variant that combines the idea from the OP's code with the above approach:
#include <stdio.h>
#include <stlib.h>
static void p(int n);
static void (*f[5])(int) = { p, p, p, p, exit };
static void p(int n) {
f[printf("%d\n", n + 101)](n + 1);
}
int main(int argc, char *argv[]) {
p(-100);
}
function p takes an integer n and prints the value of n + 101, then invokes the function whose pointer is at the offset in the array f corresponding to the number of bytes output by printf, passing n + 1 to this function.
The first call gets -100 as an argument, hence prints 1 and a newline. printf returns 2, so p calls itself recursively with the value -99.
The second call prints 2, and calls itself recursively with -98.
This process repeats until printf returns 4: the function called for f[4] is exit and since printf returns 4 when it first prints the number 100, exit gets the value 0 and terminates the program with an exit status of 0, which means success.
No loops, no conditions, no tests at all.
This relies on recursion (in function f1) and dynamic array lookups (in function foo) instead of using either loops or conditionals.
void f2(int x) //why we have used this fumction
{}
The f2 function does nothing and is called when x >= 100, thus terminating the sequence when the maximum value is reached.
void (*tab[])(int) = { f1, f2 }; // what is this
That is an array initialization. tab is an array of pointers to functions taking an int parameter. The two elements of the array are pointers to functions f1 and f2.
tab[!(x < 100)](x); // what is this
This does the same thing a conditional would in this scenario. This calls either the first or second function in tab, depending on whether x < 100 or not.
When x < 100, the array subscript !(x < 100) equals !true, or 0 when converted to an int. tab[0] is the first element of the array, the function f1. The f1 function prints and increments the number, then recurses by calling foo again, thus continuing the sequence.
When x >= 100, tab[1] is called, which is the second element of the array, f2. Since f2 does nothing, the sequence ends when x >= 100.
f1 is responsible for printing and actually incrementing the count and relies on the bouncing back and forth to foo.
tab is an array of two functions, f1 and f2. Look that, in foo, this array is indexed by a boolean expression that eventually translates to execute f1(count) until count is greater than or equal to 100.
foo, tab, f1, and f2 are, therefore, just a way to support and terminate recursion.
The call stack would look like this when the program is executed:
main()
foo(0)
f1(0) -> print 1
foo(1)
f1(1) -> print 2
foo(2)
f1(2) -> print 3
....
foo(99)
f1(99) -> print 100
foo(100)
f2(100) -> do nothing
<---------------------------------------