I have a function that does some calculations on a set of numbers recursively. I also want to print calculations in each recursion call, passing the string from the previous calculation and concatenating it with the current operation. An example output might look like this:
3
(3) + 2
((3) + 2) / 4
(((3) + 2) / 4) x 5
((((3) + 2) / 4) x 5) + 14
... and so on
So the second call gets 3 and adds + 2 to it, the third call is passed (3) + 2, etc. My prototype of a recursive function is as follows:
void calc_rec(int input[], int length, char * previous_string);
I wrote two helper functions that will help me with this operation, but they explode when I test them:
char * strapp(char * old, char * new)
{
int len = sizeof(char) * (strlen(old) + strlen(new));
char * out = (char*)malloc(len);
sprintf(out, "%s%s", old, new);
return out;
}
char * mathop(char * old, char operand, int num)
{
char * output, *newout;
char fstr[50];
sprintf(fstr, " %c %d", operand, num);
output = strapp(old, fstr);
newout = (char*)malloc( 2*sizeof(char)+sizeof(output) );
sprintf(newout, "(%s)", output);
free(output);
return newout;
}
void test_mathop()
{
int i, total = 10;
char * first = "3";
printf("in test_mathop\n");
while (i < total)
{
first = mathop(first, "+", i);
printf("%s\n", first);
++i;
}
}
strapp() (), mathop() ( "(3) +2" ), char ('+', ' - ' ..) int , "((3) +2)/3". , ? .