Home > front end >  Print number of recursions in C
Print number of recursions in C

Time:11-25

So I have an exercise that goes like this: Code a program that user inputs 2 natural numbers X and Y. The output must print the number of combinations that are recursively computed to generate binary numbers using X 1s and Y 0s. For example, user inputs 2 and 3. The combinations of 2 and 3 generating binary numbers are:

  1. 00011
  2. 00101
  3. 00110
  4. 01001
  5. 01010
  6. 01100
  7. 10001
  8. 10010
  9. 10100

10. 11000

The program must print "10".

So I've coded the recursion but I cant figure out a way to print the number "10". Here is my code

#include <stdio.h>
#include <stdlib.h>

int recursion(int a, int z)
{

    if(a==0 && z==0)
    {
        printf(".");
        return 1;
    }

    if(a!=0 && z==0)
        return recursion(a-1,z);
    if(a==0 && z!=0)
        return recursion(a,z-1);
    if(a!=0 && z!=0)
        return recursion(a-1,z) recursion(a,z-1);

}

int main()
{

    int a,z;

    scanf("%d %d", &a, &z);

    recursion(a,z);

    return 0;
}

This code only prints 10 "." instead of the number of dots that I need. Any thoughts?

CodePudding user response:

Your program already returns its level of recursion, a simple way to print it could be:

int main()
{
    int a,z,level;

    scanf("%d %d", &a, &z);

    level = recursion(a,z);
    printf("\n%d\n", level); /* Newline characters added to improve readability */
    
    return 0;
}

So the output would be the dots you are printing on line 9 and the level of recursion (10 in your example).

..........
10

CodePudding user response:

#include <stdio.h>
#include <stdlib.h>

int recursion(int a, int z)
{ int d;

    if(a==0 && z==0)
    {
        d  ;
       
        return 1;
    }

    if(a!=0 && z==0)
        return recursion(a-1,z);
    if(a==0 && z!=0)
        return recursion(a,z-1);
    if(a!=0 && z!=0)
        return recursion(a-1,z) recursion(a,z-1);

}

int main()
{

    int a,z,d;

    scanf("%d %d", &a, &z);

    d=recursion(a,z);
printf("%d",d);
    return 0;
}
  • Related