#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)
Related
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.
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'm struggling with this (optional) problem my professor recommended I try. Basically, my task is to write a program which displays all prime integers from 2-10,000 using my own user-defined function to determine prime-ness. It sounded simple enough but I'm having major difficulties debugging my program. For some reason, my code only displays 2 and 3 before ending.
#include<stdio.h>
//function declaration
int prime(int);
//main body
int main(void)
{
int x=2, y;
for (x=2;x<=30;x++)
{
y=prime(x);
if (y!=0)
printf("%d\n", x);
}
getchar();
return(0);
}
//function definition
int prime(int x)
{
int y;
for (y=2; y<=(int)sqrt(x); ++y)
{
if (x%y==0)
return 0;
}
if (y==(int)sqrt(x))
return 1;
}
Instead of returning 1 if x is prime, my prime checking function seems to return a random large number (2686xxx) but that shouldn't be an issue because all primes return 0. If I run something like:
if (y==0)
printf("%d\n", x);
I see a list of all non prime numbers. If I run something like:
printf("%d %d\n", x, y);
I see a list of all integers from 2-10,000 and the result of my prime checking function (0 for non-primes, 2686xxx for primes).
Why doesn't the opposite (y!=0) display a list of prime numbers? What is causing my code to stop after just displaying 2 and 3? Why is my prime function returning a weird integer instead of 1? Finally, I'm still a beginner but how can I write better code in general? I don't think I'm breaking any of the standard accepted practices but how can I make my code more clean or efficient?
Thanks in advance for the help!
Your loop continues if y==(int)sqrt(x). So when it finishes, they're not equal. What you wanted is:
if (y>=(int)sqrt(x))
return 1;
But this is not needed at all. Just return 1; is sufficient. You've already returned zero if the number isn't prime.
If you wanted only a single return statement:
int prime(int x)
{
bool isPrime = true;
int y;
for (y=2; y<=(int)sqrt(x); ++y)
{
if (x%y==0)
{
isPrime = false;
break;
}
}
return isPrime;
}
Don't use the sqrt() function. In mathematics if you have 'x = sqrt(y)'. If you square both sides you will get something like this 'x * x = y'. This expression in c is tremendously faster than the sqrt function. Thus instead of doing:
y <= (int)sqrt(x)
Have you for loop guard be something like this:
y * y <= x
Here is a running example of your problem:
Primes 2 -> 10000
At the end of your prime function just return 1. If it wasn't prime it would have returned 0 earlier. Right?
As it is you've made a function which sometimes returns nothing at all. Which means that it returns whatever random value happens to be in the register.
You can use sieve of eratosthenes or sieve of atkin to mark all the prime numbers in an array and then display the prime numbers. It will be time efficient although it incurs some space complexity.
e.g if you want to display prime numbers from 1 to 10
Leave of 1. Its not a prime. Its neither prime nor composite.
So start from 2.
consider this array of size 10 = 2 3 4 5 6 7 8 9 10
Traverse from 2. If an element is not highlighted highlight all its multiples.
i.e for 2 highlight its multiples 4 6 8 10
==> 2 3 4 5 6 7 8 9 10
For 3 do the same
==> 2 3 4 5 6 7 8
9
10
Then do it for the rest of the no.s i.e. 5 and 10 (Here 7 dont have multiple)
Finally print the non highlighted elements. 2,3,5,7.
Repeat this procedure for any other ranges.
Since you are interested in writing computer programs for prime numbers, perhaps you would like to turn this paper into a computer program. It deals with prime numbers and is similar to the sieve you were trying to create in C.
https://graviticpropulsion.files.wordpress.com/2015/04/prime-number-theory.pdf
I'm not sure if it is faster or less memory intensive, but I'm curious myself how high of a prime number it can find before it becomes too intensive for a computer.
Program:
int main( )
{
printf("%d",printf("%d %d",5,5)&printf("%d %d",7,7));
return 0;
}
Output:
5 57 73
I am new to C, I could guess where the 5 57 7 came from, but no idea where the 3 came from. Can someone explain the output?
If you apply binary AND to 3 and 3 (which are the return values of both nested printf calls) you get 3 as result.
Note that the code actually contains undefined behaviour, since the order of the nested calls isn't defined.
The return value of the printf function is the number of characters transmitted, or a negative value if there is an error.
printf("%d %d",5,5) returns 3 if there is no error
printf("%d %d",7,7) also returns 3 if there is no error
So printf("%d %d",5,5) & printf("%d %d",7,7) is 3 & 3 which is evaluated to 3.
3 is the Bitwise AND of the values returned by two printf.
printf returns the numbers of characters printed.
In your case, printf("%d %d",5,5) has printed three characters that are two 5 and one space, similarly printf("%d %d",7,7) is also printing two 7 and one space. Hence both printf is returning 3.
so, 3 is the result of 3 & 3
as you can see here : http://en.wikipedia.org/wiki/Printf_format_string, printf return the number of printed chars, so:
printf("%d",printf("%d %d",5,5)&printf("%d %d",7,7));
is composed of :
printf("%d %d",5,5) return 3 (5 space and 5) and print 5 5
printf("%d %d",7,7) return 3 (7 space and 7) and print 7 7
At this stage we got : 5 57 7
And 3 & 3 = 3, finally you got this output:
5 57 73
Regards.
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
$