Can someone please explain to me why in the following code, after it prints out 1 consecutively , the value for a increases again? Shouldn't it stop there, after the second 1?
#include <stdio.h>
void f(int a)
{
printf ("%d\n",a*a);
if (a>1)
f(a-1);
printf ("%d ",a*a);
}
int main()
{
f(5);
return 0;
}
The output is
25
16
9
4
1
1 4 9 16 25
Each recursively called function prints the passed value multiplied by itself two times
void f(int a)
{
printf ("%d\n",a*a);
//...
printf ("%d ",a*a);
}
In the last recursive call the value of a is not greater than 1. So the function outputs (I do not take into account the difference in the calls of printf relative to the new line character '\n')
25 <- first call
16 <- second call
9 <- third call
4 <- forth call
1 <- fifth call
1 <- fifth call
4 <- forth call
9 <- third call
16 <- second call
25 <- first call
That happens because you're printing twice. Just need once. Test:
#include <stdio.h>
void f(int a) {
printf ("%d\n",a*a);
if(a>1)
f(a-1);
}
int main() {
f(5);
return 0;
}
The output is now:
25
16
9
4
1
You are presenting a really nice example of recursion.
What is happening here is that the first print, the one at the top of the function is printing the first sets os a*a, while the final print comes from the end of the recursion, let's say, when the recursion is done is printing in its way out.
Printouts before the recursion calls.
25
16
9
4
1
1 4 9 16 25 -> line from recursion.
Related
#include <stdio.h>
void PrintNumPattern(int x, int y)
{
if (x > 0)
{
printf("%d ", x);
PrintNumPattern(x - y, y);
printf("%d ", x);//idk why this makes it work...why does it add?
} else {
printf("%d ", x);
}
}
int main(void) {
int num1;
int num2;
scanf("%d", &num1);
scanf("%d", &num2);
PrintNumPattern(num1, num2);
}
So currently I am learning about recursion and how it works. The code above is supposed to get an input, for example, 12, 3 and then output 12 9 6 3 0 3 6 9 12.so far I am so confused. Why does the printf,that I put a comment on, start adding after 0? The program only gets told to subtract not add. Also how does the program know to stop at 12?
start adding after 0?
It never adds anything. It's just that there are two printf calls in the first condition that print the same number - once before the recursive call and once after it.
Also how does the program know to stop at 12
The recursive call stops at 0. Then it returns to the parent call which will print it's number.
It will help if you write out the call tree. I've tried to visualise it as shown below. Each indent represents a function call from a parent function. On the right hand column I show the resulting output.
PrintNumPattern(12, 3)
printf(12) -------------------------> 12
PrintNumPattern(9, 3)
printf(9) ----------------------> 9
PrintNumPattern(6, 3)
printf(6) ------------------> 6
PrintNumPattern(3, 3)
printf(3) --------------> 3
PrintNumPattern(0, 3)
printf(0) ----------> 0
printf(3) --------------> 3
printf(6) ------------------> 6
printf(9) ----------------------> 9
printf(12) -------------------------> 12
Another way to look at it which may (or may not) be helpful is to visualise just one level of the recursive call. This clearly shows that there is no "addition" but only a repetition.
PrintNumPattern(12, 3)
printf(12) -------------------------> 12
PrintNumPattern(9, 3) --------------> 9 6 3 0 3 6 9
printf(12) -------------------------> 12
The reason the second printf was necessary is that you want to repeat what you printed on the way down to 0. It may look like you're adding but all you're doing is repeating your printf calls in reverse. Visualizations either by hand or tool can help build an intuition for recursive functions. See this example for a visualization of PrintNumPattern(2, 1)
void abc(int n) {
if (n <= 10) {
abc(++n);
printf("%d\n", n);
}
}
void main() {
int m = 5;
abc(m);
}
The output shows:
11
10
9
8
7
6
I cannot understand the output. Please explain. I am a novice code lover.
The sequence of events is this:
main calls abc(5).
abc(5): n is <= 10, hence n is incremented to 6, calling abc(6).
abc(6): n is <= 10, hence n is incremented to 7, calling abc(7).
abc(7): n is <= 10, hence n is incremented to 8, calling abc(8).
abc(8): n is <= 10, hence n is incremented to 9, calling abc(9).
abc(9): n is <= 10, hence n is incremented to 10, calling abc(10).
abc(10): n is <= 10, hence n is incremented to 11, calling abc(11).
abc(11): n is not <= 10, function returns without any output.
back to abc(10): its own n variable is still 11, printf prints 11, function returns.
back to abc(9): its own n variable is still 10, printf prints 10, function returns.
back to abc(8): its own n variable is still 9, printf prints 9, function returns.
back to abc(7): its own n variable is still 8, printf prints 8, function returns.
back to abc(6): its own n variable is still 7, printf prints 7, function returns.
back to abc(5): its own n variable is still 6, printf prints 6, function returns.
main returns
Complete output:
11
10
9
8
7
6
Each instance of abc() has its own value for local variable n, which explains why the values printed by the different instances are different.
Note that you should also:
include <stdio.h>
define main with this prototype: int main(void)
for good style, add a return 0; statement at the end of main.
I would first suggest you to read basics of recursion. It will be good for you.
Now about All the recursive calling, it will be like as bellow:
abc(5);
This will call the function abc with value 5.
Now before printing it, it will make the recursive call to abc but before calling it will increment the value of n from 5 to 6. The same will happen in the next call from 6 to 7, 7 to 8, 8 to 9, 9 to 10 and 10 to 11. Now on the call for n=11, the if condition will fail and recursion will stop. On returning from recursive calls, it will print increment values but from last call to first,i.e. for 11 than 10 and so on till 6.
void abc(int n)
{
if (n<=10)
{
abc(++n);
printf("%d\n",n);
}
}
void main()
{
int m=5;
abc(m);
}
When main is called, a variable m is initialized to 5.
abc is then called and the 5 is passed to it.
When abc first executes, n = 5. If n is less than or greater than 10, abc is called again but this time with 1+n. Therefore, since 5 is less than 10, abc is called and 6 is passed to it.
First off in these lines of code, what is the output?
printf("7\n");
printf("6\n");
If you guess 7 before 6 you are correct. If you call two functions that prints something, the one called first will output first. This is very important
Lets first rewrite your function so that each line doesn't do separate things. I'm thinking of the mutating ++n:
void abc(int n) {
if (n <= 10) {
n = n + 1;
abc(n);
printf("%d\n", n);
}
}
So if you pass 9 to this it will first change n to 10, then call abc(10) and get the output of that before it prints 10. The call to abc(10) increases its n to 11 and calls abc(11) first, which doesn't do anything, then does its printf "11\n" and returns to the call where n is 10 and do its printf "10\n" before it returns to the initial call.
The output is:
11
10
If you do abc(5) it works the same. abc(6) needs to output first. And in abc(6) abc(7) needs to output first all the way to 11 thet doesn' have output and then it goes back, prints 11, 10, .... n + 1.
You can do it the other way around!
Lets say you start at the base case abc(11) and see the code doesn't do anything.
Then you look at abc(10). You see it will first increase n to 11, then call abc(11) which we previously saw does nothing and then it prints n, thus 11. Thus abc(10) prints "11\n".
If you look at abc(9) you see that n increases to 10, then it calls abc(10). You already know that that it prints "11\n", then it does its printf adding `"10\n" to the output, thus:
11
10
Now if you do this with one number lower you eventually get to abc(5).. It increases n to 6, then calls abc(6) which you know outputs "11\n10\n9\n8\n7\n" and then it does the next line that prints "6\n" making the output of abc(5) "11\n10\n9\n8\n7\n6\n"
To make the function clear exclude the recursive code of it itself the following way
void abc(int n)
{
if (n<=10){
++n;
printf("%d\n",n);
}
}
So if the function is called with argument equal to 5 then the function outputs 6. If the function is called with argument equal to 10 then the function outputs 11 due to the expression statement
++n;
Now just add the recursive call the following way
void abc(int n)
{
if (n<=10)
++n;
{abc( n);
printf("%d\n",n);
}
}
and you will get the described result.
Take into account that according to the C Standard the function main shall be declared like
int main( void )
I'm working on a program that can convert number to its binary form.
With help, I was able to get this, and it seems to work but I just don't understand how. I guess the best way to do this is to try to explain how I think this is working and someone can correct me.
I have a function that has an if statement that says if n divided by 2 isn't equal to 0 then divide n by 2. Then it prints the remainder if n /2 so either 1 or 0.
The main function just runs the function with whatever number I give it, in this case 456.
But how does the program know to run the function multiple times to get the entire binary form?
I feel like this isn't that complicated but I'm not getting it.
#include <stdio.h>
void ConvertToBinary(int n)
{
if (n / 2 != 0) {
ConvertToBinary(n / 2);
}
printf("%d", n % 2);
}
int main (){
ConvertToBinary (456);
return 0;
}
The function ConvertToBinary is recursive, meaning it calls itself. At some point the function needs to know when to stop calling itself. This is called the base case.
On the first call to this function, n=456. In this case n/2 != 0 is true, so the function calls itself, this time with 228. It keeps calling itself until it gets passed a value where n/2 != 0 is false, which is the base case. The innermost call to the function then prints n % 2 and returns. The next innermost call also prints n % 2 for its value of n, and so on up the call stack.
So the function calls look something like this:
ConvertToBinary(456)
ConvertToBinary(456/2=228)
ConvertToBinary(228/2=114)
ConvertToBinary(114/2=57)
ConvertToBinary(57/2=28)
ConvertToBinary(28/2=14)
ConvertToBinary(14/2=7)
ConvertToBinary(7/2=3)
ConvertToBinary(3/2=1)
print 1%2=1
print 3%2=1
print 7%2=1
print 14%2=0
print 28%2=0
print 57%2=1
print 114%2=0
print 228%2=0
print 456%2=0
Result:
111001000
Step through it line by line on a piece of lined paper. Use indention as you make recursive calls, then unindent as you return. Place the output in the right column of your paper.
I would start with simple numbers like 1, 4, 7, 10, then try 456.
This is my first answer here but I'll try and explain as best I can. This is an example of recursion (Google that) which is a powerful tool for solving certain kinds of problems. The trick is that the method calls itself, so tracing it through (with a smaller example):
1st call
n = 13
call ConvertToBinary with 13 / 2 = 6
2nd call
n = 6;
call ConvertToBinary with 6 / 2 = 3
3rd call
n = 3
call ConvertToBinary with 3 / 2 = 1
4th call
n = 1
1 / 2 = 0 so continue through!
print 1 % 2 = 1
method exits and returns to the 3rd call
3rd call again
print 3 % 2 = 1
method exits and returns to the 2nd call
2nd call again
print 6 % 2 = 0
method exits and returns to the 1st call
1st call again
print 13 % 2 = 1
and done!
Now we have 1101 which is 13 in binary,
#include <stdio.h>
void ConvertToBinary(int n)
{
// is the number passed in 2 or greater? If so, print out the smaller binary digits first.
if (n / 2 != 0) {
// this is a recursive call. It won't return until all the smaller binary digits have been printed.
ConvertToBinary(n / 2);
}
// all the smaller digits have been printed, time to print out the current binary digit.
printf("%d", n % 2);
}
int main (){
ConvertToBinary (456);
return 0;
}
I have a code which includes a recursive function. I have wasted a lot of time on recursion but I still couldn't get it really:
#include<stdio.h>
void count(int);
int main()
{
int x=10,z;
count(x);
}
void count(int m)
{
if(m>0)
count(m-1);
printf("%d",m);
}
When the 1st time count is called with argument as 10. it fulfills the condition and then here starts the recursive part. what happens really when a function calls itself? I don't get it. Please explain with reference to stacks.
While m is greater than 0, we call count. Here is a representation of the stack calls:
count (m = 10)
count (m = 9)
count (m = 8)
count (m = 7)
count (m = 6)
count (m = 5)
count (m = 4)
count (m = 3)
count (m = 2)
count (m = 1)
count (m = 0)
printf 0
printf 1
printf 2
printf 3
printf 4
printf 5
printf 6
printf 7
printf 8
printf 9
printf 10
next time it calls itself it has a smaller value
count(int m)
{
if(m>0)
count(m-1); // now it is calling the method "count" again, except m is one less
printf("%d",m);
}
So first it will call count with 10, then it will call it with 9, then 8, then 7..... all the way until this if statement isn't true:
if(m>0)
What might be confusing you is the if statement only applies to the next line (printf isn't part of the if statement)
so you have:
count(int m)
{
if(m>0)
{
count(m-1); // now it is calling the method "count" again, except m is one less
}
printf("%d",m);
}
So, the recursive calls will stop once m is not > 0, and then it will call the printf.
After it calls printf for when m is 0, then it will return from that 'count' call, (Back to where m was equal to 1), and then it will call the printf when m is 1, and then when m is 2, .....
So the output should be:
"0 1 2 3 4 5 6 7 8 9 10"
EDIT:
In terms of a stack:
This is what the stack is doing:
count(10) // push count(10)
->
count(9) // push count(9)
count (10)
->
...
->
count(0) // push count(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
-> (and then it starts printing and popping the method off the stack)
// pop count(0), and printf(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
// pop count(1), and printf(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
...
->
// pop count(9), and printf(9)
count(10)
->
// pop count(10), and printf(10)
When a function is called the return address (of the next code to execute) is stored on the stack along with its current arguments. Once the function finishes the address and arguments are popped so the cpu will know where to continue its code execution.
Let's write the addresses of the function (for the purpose of this example only)
count(int m)
{
(address = 100) if(m>0)
(address = 101) count(m-1); // now it is calling the method "count" again, except m is one less
(address = 102) printf("%d",m);
}
For m = 1:
The if is fullfield so we execute code at address 101 with m = 1. address 102 and m = 1 are pushed to the stack and the function is executed again from address 100 with m = 0. Since m = 0 we execute address 102 and printing 0 on console. The function ends and the last return address (102) and argument m = 1 are popped and the line at address 102 is executed printing 1 on the screen.
The function count is called with an integer argument of 10.
Since the function argument m which is 10 is greater than 0 the function count calls itself with an integer argument of m which is 10 minus 1 which equals 9.
Step 2 repeats with varying arguments (m-1) until m is not greater than 0 and which point the program prints the value of m.
The recursive function just modifies the parameter given to it and calls itself with that modified value until the desired result is returned (in this case m not being greater than 0).
Each number refers to the line number.
#include<stdio.h>
count(int);
main()
{
1int x=10,z;
2count(x);
}
count(int m)
{
3if(m>0)
4 count(m-1);
5printf("%d",m);
}
The execution happens like this(with x=3) -
line number|value of x
1 3
2 3
3 3
4 2
3 2
4 1
3 1
4 0
5 0
5 1
5 2
5 3
Numbers printed on the screen 0 1 2 3
If you want a more specific answer, then you have to look into how compilers work. But generally speaking the compiler will create machine code for the function that includes a preamble, in this code enough memory is allocated on the stack (by decrementing a stack pointer) that a copy of the functions variables can be placed on the stack (we can store the state of the function).
The function will have values stored in registers and memory and these must be stored on the stack for each (recursive) call, otherwise the new call will overwrite the precious data!. So very basically the machine code looks like this (pseudo code)
//store m on the stack
store m,stack_pntr+m_offset
//put input values in designated register
a0 = m
//allocate memory on the stack
stackPntr -= stack_size_of(count_vars)
//store return address in allocated register
//jump to the first instruction of count
.
.
By changing some data used for computation we can go back and read the same instructions again and get a different result. The abstraction of recursive function allows us to manipulate the data we want to change in a nice "call by value" way so that we don't overwrite it unintentionally.
This is done by the compiler when it stores the state of the calling function on the stack so we don't have to manually store it.
I am trying to understand the output of the program printed below. When I look at it, I see that when printnum() is called with an argument of 1, "1" will be printed and then since 1<7, the function will call itself. This process will continue until "6" is printed and then printnum(7) is called. So, now "7" is printed and the if condition is not satisfied, so that code is skipped and we move to the second printf("%d", x) function where "7" is printed out again. There is nothing after the second printf("%d", x), so why doesn't everything end there? What makes the program keep going to print the numbers again in descending order?
#include <stdio.h>
int printnum ( int x )
{
printf("%d", x);
if ( x < 7 )
{
printnum ( x + 1 );
}
printf("%d",x);
}
int main()
{
printnum(1);
}
Output:
12345677654321
printnum(8) is never called, because it isn't true that 7 < 7.
The reason that you get the numbers printed in descending order once x = 7 is reached is, that each recursive call ends, leaving the previous call to continue.
Consider what it does for x = 1:
Print 1
Call recursively with x = 2
Print 1
If we expand this one level more:
Print 1
Print 2
Call recursively with x = 3
Print 2
Print 1
And one more:
Print 1
Print 2
Print 3
Call recursively with x = 4
Print 3
Print 2
Print 1
If you continue this expansion, you can see you get numbers in ascending order before the recursive call, and in descending order after the recursive call.
This happens because the second printf is called after your recursion exits at each level.
As your final recursive call printfs and ends, control transitions to the function that called it - the second-to-last recursive call. This call then exits the scope of the if statement, and calls printf, and then ends - upon which control transitions to the function that called it - the third-to-last recursive call. Repeat until you are inside the call to printnum(1), whose return takes you back to main.
It's recursion. When you enter the function you call printf, then you enter another level in the recursion, then you enter the printnum, so you call the printf with x+1 and so on.
When you arrive at stop condition (x==7), the function goes till the second printf (so 7 will be displayed again).
The function printnum terminates, so the program returns at the level above, then printnum at level 6 can printf again, terminate and return and so on.
Comments in-line!
int printnum ( int x ) x = 1 x = 2 x=6 x=7
{
printf("%d", x); prints 1 prints 2 prints 6 prints 7
if ( x < 7 ) Yes Yes Yes No
printnum ( x + 1 ); calls printnum(2) calls printnum(3) .... calls printnum(7) N/A
printf("%d",x); print 2 and return to print 6 and return prints 7 and returns to the
the caller which is the previous caller to the previous previous caller which is
main() which is printnum(1) caller which is printnum(x=6)
printnum(5)
}
Please check the following to print in ascending and descending order passing the starting value and the limit.. (please note that the error checking is not done!)
#include <stdio.h>
int printnum_123(int x, int limit)
{
printf("%d ", x);
if (x<limit)
printnum_123(x+1, limit);
return;
}
int printnum_321(int x, int limit)
{
if (x<limit)
printnum_321(x+1, limit);
printf("%d ", x);
return;
}
int main(void)
{
printnum_123(1, 10); printf("\n");
printnum_321(1, 10); printf("\n");
return 0;
}
$ ./a.out
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
$