# recursive algorithm

• 07-18-2004
vienne
recursive algorithm
i'm having a problem with below recursive code.
there are 4 chars stored in a array, 'a', 'b', 'c', 'd'. input is between 1 and 16, and output should look like this:

when input is 1:
a
b
c
d

when iput is 2:
aa
ab
ac
ba
bb
bc
bd
ca
cb
cc
cd
da
db
dc
dd

and so on...

here is the code i'v been working:
Code:

```void f(int x, int num) {         int i;         char a[4] = {'a', 'b', 'c', 'd'};         char temp[16];         if(num == 0)                 return;         else                 for(i = 0; i < 4; i++)                 {                         temp[x] = a[i];                         f(x + 1, num - 1);                         temp[x + 1] = '\0';                         printf("%s\n", temp);                 } }```
where should i change to make it work?
• 07-18-2004
sean
What isn't working now? You need to be more specific about that so we know where to look.
• 07-18-2004
vienne
Quote:

Originally Posted by sean_mackrory
What isn't working now? You need to be more specific about that so we know where to look.

ok...
when u run the above code, u get this result:
Code:

```\$ ./test.out Enter a number between 1 and 16: 1 a b c d \$ ./test.out Enter a number between 1 and 16: 2  a  b  c  d a  a  b  c  d b  a  b  c  d c  a  b  c  d d```
here is the full code:
Code:

```#include <stdio.h>   void f(int, int, int);   int main(void) {         int x = 0, num;           printf("Enter a number between 1 and 16: ");         scanf("%d", &num);           if (num < 1 || num > 16)                 printf("-> %d is not a valid number.\n", num);           else                 f(x, num, num); }   void f(int x, int n, int num) {         int i;         char a[4] = {'a', 'b', 'c', 'd'};         char temp[16];           if(num == 0)                 return;           else                 for(i = 0; i < 4; i++)                 {                         temp[x] = a[i];                           f(x + 1, n, num - 1);    // here?                           temp[x + 1] = '\0';                           printf("%s\n", temp);    // and maybe here?                 } }```
• 07-18-2004
Thantos
I like these types of problems. Always good for a little dusting of the skills :)
Here is my solution done up as much like yours as possible. Things I would notice: When I do the print, how I declared the array (note you don't have to do yours dynamically I did just for kicks)
Code:

```#include <stdio.h> #include <stdlib.h> void f(const int num, const int pos) {   static const char a[4] = {'a', 'b', 'c', 'd'};   static char *array;   int counter;   if ( pos == 0 )     array = malloc (num + 1);   if ( pos >= num )   {     array[num] = '\0';     puts(array);     return;   }   for (counter=0; counter<sizeof a; counter++)   {     array[pos]=a[counter];     f(num, pos+1);   }   if ( pos == 0)     free(array); } int main(void) {   f(3,0);   putchar('\n');   return 0; }```
• 07-18-2004
vienne
thanks alot, Thantos.