C programming , recursion - c

#include <stdio.h>
void main(){
static int n=7;
if(n){
n--;
main();
printf("%d",n);
}
}
Sol: I was trying to trace the recursion. In my logic answer should be 1234567, but the answer is 000000. My question is how to trace this recursion?

That is because you are calling main before printing.
if you do:
#include <stdio.h>
void main(){
static int n=7;
if(n){
n--;
// main();
printf("%d",n);
main();
}
return;
}
You will get the output: 6543210
But in your case, it will print only when the value of n is 0. And since 7 print is pending therefore 0000000

There exists only one variable since it's static. A slight modification (including the fix of void return type) demonstrates it:
#include <stdio.h>
int main(void)
{
static int n=7;
if(n) {
n--;
printf("%d",n);
main();
printf("%d",n);
}
}
Output:
65432100000000

The best way to trace it probably is using gdb to follow it along.
If you declare n as static, it's value would be preserved across function calls. Note that you are calling printf after the recursive step (calling main). This causes printf to see the value of n after all the calls to main.
Think of this sequence, executing with n = 2
if (n) // first time, n == 2.
n--; // n == 1
main();
if (n) // second time, n == 1
n--;
main();
if (n) // third time, n == 0, fails
printf("%d",n); // n == 0.
printf("%d",n); // n == 0.

Related

Why does my FirstFactorial program keep looping back to while condition even after the condition is not met

Here's the code snippet, this when run with number 4 outputs 2424242448484848288288288288576576576576. Not sure as to why would the execution would jump back to while loop after exiting the function code. Any help will be appreciated. Thank you in advance.
#include <stdio.h>
#include <string.h>
int result = 1;
void FirstFactorial(int);
void FirstFactorial(int num) {
// code goes here
while (num > 0) {
result = result * num;
num--;
FirstFactorial(num);
}
printf("%d", result);
}
int main(void) {
int var;
// keep this function call here
printf ("Enter your no.\n");
scanf("%d", &var);
FirstFactorial(var);
return 0;
}
Within the function
void
FirstFactorial(int num)
{
// code goes here
while(num > 0)
{
result = result * num;
num--;
FirstFactorial(num);
}
printf("%d", result);
}
each its iteration calls itself num times and all iterations together output the global variable result.
So for example in the first call of the function the function calls itself in the while loop for the range of values [num, 1].
Remove the while loop and do not use the global variable.
Here is a demonstrative program.
#include <stdio.h>
unsigned long long int factorial( unsigned long long int n )
{
return n < 2 ? 1 : n * factorial( n - 1 );
}
int main(void)
{
printf( "%llu! = %llu\n", 4llu, factorial( 4 ) );
printf( "%llu! = %llu\n", 20llu, factorial( 20 ) );
return 0;
}
The program output is
4! = 24
20! = 2432902008176640000
Pay attention that the maximum value you may specify is 20.
Either you implement the factorial with a loop or you do it recursively.
Both ways are feasible but your code mixes it up.
Your function mixes iterative and recursive approaches. You can correct it by removing the useless recursion which causes multiple intermediary results to be computed and printed. Defining result as a global variable is also a mistake, especially since you do not reinitialize it before the loop. Using type long long will allow for larger factorials to be computed. Adding a trailing \n after the printf conversion specifier is advisable too.
Here is a corrected version:
#include <stdio.h>
void FirstFactorial(int num) {
long long result = 1;
while (num > 1) {
result = result * num;
num--;
}
printf("%lld\n", result);
}
int main(void) {
int var;
// keep this function call here
printf("Enter your number\n");
if (scanf("%d", &var) == 1)
FirstFactorial(var);
return 0;
}

Why is needed here to have if statements in the function in order to work?

When I tried to implement fibonacci sequence using recursion in C, I noticed that in my function fibo if I didn't use some kind of if statements that return 1 out of the function the program crashed.Why did this happens?
#include<stdio.h>
int fibo(int);
int main(void){
int n, num;
scanf("%d", &n);
num = fibo(n);
printf("apo: %d", num);
return 0;
}
int fibo(int n){
if(n==0)
return 0;
else if(n==1)
return 1;
else if(n!=0){
n = fibo(n-1) + fibo(n-2);
return n;
}
}
/*FOR EXAMPLE if I leave the fuction like this, it doesn't work*/
int fibo(int n){
n = fibo(n-1) + fibo(n-2);
return n;
}
Let's take the absolute simplest case of a recursive function.
int foo(int n)
{
return foo(n-1);
}
If you want to calculate foo(5) then the function foo will need to calculate foo(4) before returning. But same goes for foo(4). It has to calculate foo(3) first. So there is no value for n where the function does not need to call itself, thus recursing indefinitely. In theory that is. In practice it will crash.
Those cases that does not cause a recursive call are called base cases.
Your function needs a limit(base case) to no longer to execute itself, If you don't have the statement "if" to decide when to jump out of the function, your following program can't be executed. and the function won't stop execute until your program collapses.

Segmentation fault with recursive factorial implementation

Now I am practicing using Vim on Linux.
I made a simple code like this
#include <stdio.h>
int factorial(int n){
if (n<0) { return 0; }
else if (n==0) { return 1; }
else { return n * factorial(n); }
}
int main(void){
int n = 0;
printf("Put n value : ");
scanf("%d", &n); /* non-OP inserted ";" to help people focus on the problem */
printf("%d! = %d\n", n, factorial(n));
return 0;
}
When I put -1 and 0, it works. They return 0 and 1.
However, when I put positive integer values on n, it didn't work.
I tried to find out the reason so I used gdb,
but it just said like this :
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400620 in factorial ()
What's wrong with my code? I even cannot understand the point.
When n > 0 your recursive program never terminates. The value of n is never decremented and so it continues running recursively until your run out of memory.
It should be return n * factorial(n-1);
You code is causing stack overflow. In the given function n is never decremented. Last statement should be
else { return n * factorial(n-1); }

Fibonacci sequence while loop

I have to write code that displays the Fibonacci sequence to the user desired number of terms and must also use a while loop. I'm not sure why this code isn't working.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int max;
printf("Enter the max term of the Fibonacci Sequence:\n");
scanf("%i", &max);
int a=0;
int b=0;
a=2;
while(a<max) {
if((a==0||a==1))
{
printf("%i\n", &a);
++a;
}
else if(a>1)
{
a=(a-1)+(a-2);
printf("%i\n", &a);
++a;
}
}
return 0;
}
You can try this.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int max;
printf("Enter the max term of the Fibonacci Sequence:\n");
scanf("%i", &max);
int n=0;
int a=0;
int b=1;
int next;
while(n<max) {
if ( n <= 1 )
{
next = n;
n++;
}
else
{
next = a + b;
a = b;
b = next;
n++;
}
printf("%d\n", next);
}
return 0;
}
issues with your code:
following declaration & initialisation, you set a=2 => it won't take the true branch of the if statement -- '0' will not be printed in your result.
a=(a-1)+(a-2); i.e a = 1
then you are doing ++a; => a == 2. thus it again else statement with same a==2.
hence it will print the same value and loop executes infinitely.
In the very beginning of your program (before the while loop) a is 2 (see the line a=2).
And in the while loop you do following:
a=(a-1)+(a-2); // a = 2-1+2-2 i.e. a = 1
and right after it
++a; // a == 2
So, after it a==2 again. This loop never ends.
But it is technical problem. More important is that you are trying to calculate not Fibonacci Sequence. In the Fibonacci Sequence each subsequent number is the sum of the previous two. But in your code there is adding of not two previous numbers of Fibonacci Sequence, but previous two Natural numbers.
You have variable b, because someone told you to add it. And it was right! Just remember previous found element of the Fibonacci Sequence in b. When you know previous one element and current one, it is possible to calculate next one.

Debugging a recursive function

#include<stdio.h>
void binary(int n)
{
int bin=0;
if(n!=0)
{
bin=n%2;
binary(n/2);
}
printf("%d",bin);
}
void main()
{
int a;
printf("Decimal value: ");
scanf("%d",&a);
binary(a);
}
When I tried to run above code, it outputs the binary value of the decimal number a preceding with one 0. As I have used recursive function here, it also puts the initial value of bin (i.e. 0) on stack and prints that 0 as well. But I want to display only binary values not that preceding 0.
I would be glad if anyone suggest me how to make this function not to store that initial value of bin on stack.
Try this.
#include<stdio.h>
void binary(int n)
{
bin=n%2;
if(n/2!=0)
binary(n/2);
printf("%d",bin);
}
void main()
{
int a;
printf("Decimal value: ");
scanf("%d",&a);
binary(a);
}
Since it checks whether n/2 == 0 before calling binary() it never prints the intial 0.

Resources