Search code examples
crecursioncounter

how to make a recursive counter


I'm trying to make a counter function that takes n as an argument so if n is 2 the result would be 01, 02, 03, ..., 99 and if n is 3 the result would be 001, 002, ..., 999 and so on I'm new to recursion and couldn't find a way to do it so I decided to make a solution for n = 2 then I'll try to generalize it
but unfortunately I couldn't. My solution for n = 2 is:

#include <stdio.h>

void    allPossibleComb(void)
{
    char    counter[2];

    counter[0] = '0';
    counter[1] = '0';
    while (counter[0] <= '9')
    {
        counter[1] = '0';
        while (counter[1] <= '9')
        {
            printf("%c%c ", counter[0], counter[1]);
            counter[1]++;
        }
        counter[0]++;
    }
}

int main(void) {
  allPossibleComb();
  return 0;
}

So for n = 2 I needed two while loops the conclusion I had if n = 9 I'll need 9 while loops and that pushed to think of a recursive solution

I made a lot of attemps but I just couldn't get it so here the code of my last attempt which won't make any sense but I'll just put it here

void recursive_counter(int n,int c, char seq[])
{
    
    if(seq[n] == '9'){
        seq[n] = 0;
        return;
    }

    while(seq[c] < '9')
    {
        seq[c]++;
        print_sequence(seq);
    }
    recursive_counter(n, c+1, seq);
}

n is length of array, c supposed to be an index and seq is an array ['0', '0'].

How can I approach such recursive problems? Note: it's a task where I can't use for loops and I can't use integers


Solution

  • You could do something like this to use recusion, and the while loop is short enough and constant length so if you really wanted to you could get rid of it. You should be able to call allPossibleComb(2) and get the same output as your working function.

    void recursive(unsigned int n, const char* str, unsigned int length)
    {
        if (!n) {
            // if n == 0 we are passed the final layer and should print
            printf("%s ", str);
            return;
        }
        
        // buffer for print
        char buffer[21];
        // copy the input string so we don't change it
        strcpy(buffer, str);
        // add the next digit + null terminator
        buffer[length] = '0'-1;
        buffer[length+1] = '\0';
        do {
            // increment digit in current layer and recurse
            buffer[length]++;
            recursive(n - 1, buffer, length + 1);
        } while (buffer[length] != '9'); // continue looping until we have done all digits '0' to '9'
    }
    
    // call recursive without having to put in initial values for some of the arguments
    void allPossibleComb(unsigned int n)
    {
        recursive(n, "", 0);
    }
    

    allPossibleComb doesn't do anything here but call recursive for you with the starting values for str and length