tekknolagi
tekknolagi

Reputation: 11012

Transform iterative function to recursive function

I was having a discussion with a coworker about how to transform the following iterative function into a strictly recursive function. We know that all iterative functions can be transformed into recursive functions; however, my coworker remembered that this particular implementation used only three parameters. We can't re-solve this problem. Are we remembering incorrectly? Or are we missing something simple?

void iterative_function (char a, char b, int width) {
  int i = width;
  while (i > 0) {
    cout << string(i, a) << string(width-i, b) << endl;
    i -= 2;
  }
  i = width % 2;
  while (i <= width) {
    cout << string(i, a) << string(width-i, b) << endl;
    i += 2;
  }
}

Where the output looks something like below when called like iterative_function('X', '-', 5).

XXXXX
XXX--
X----
XXX--
XXXXX

EDIT: Here is a small skeleton of what the recursive version might look like:

void recursive_function (char a, char b, int width) {
  if (width > -1) {
    cout << string(width, a) << endl;
    recursive(a, b, width - 2);
    cout << string(width, a) << endl;
  }
}

Except the problem here is filling the right side out with, say, hyphens.

Upvotes: 1

Views: 231

Answers (1)

Lrrr
Lrrr

Reputation: 4817

Here is the recursive function, I just add another len to your function you can see in here, that its output is exactly like the output of your code here.

#include <iostream>
using namespace std;

void i_f(char a, char b, int width,int len) {

  if(len <0 || width < 0)
    return;
  cout <<string(width, a) << string(len, b) << endl;
  i_f(a,b,width-2,len+2);
  cout <<string(width, a) << string(len, b) << endl;
}

int main() {
    i_f('X', '-', 5,0);
    return 0;
}

your code output:

XXXXX
XXX--
X----
X----
XXX--
XXXXX

my code output:

XXXXX
XXX--
X----
X----
XXX--
XXXXX

P.S After I posted my answer I saw your edit, although you edited your question 10 minutes before my answer, and I can see that you choose a path like my answer yourself.

Upvotes: 1

Related Questions