开发者

How to indent lines using recursion?

Trying to achieve something like this using recursion:

if (m > n) return;
Foo 1          // no tabs
   F开发者_Python百科oo 2       // \t
      Foo 3    // \t\t
   Foo 2       // \t
Foo 1          // no tabs

I have a function that takes 2 parameters: void indent(int m, int n); (calling number from m to n).

So far I figured this much out:

  • As long as m <= n, keep calling the function. (base case)
  • Print the first line without any tabs setw(0)
  • Call the function recursively with m+1 increment. setw(4*m)
  • Print the first line without any tabs (again). setw(0)

Am I on the right track? Is my pseudocode correct at least?

Also, is there any way to express tabs numerically? I can't think of any way to use tab \t using either recursion or iteration.

Update: I figured it out :). cout << setw(4*m); right before cout << "Foo"; does the trick. On first call m=0 so setw(0), on 2nd call setw(4), then setw(8) and so on. Now I just have to print the text backward to 0 tabs.


Looks like you are on the right path. You would just want your recursive method to check when m == n, you would only print the line once rather then twice and then unroll.


This will work perfectly.

void indent( int m, int n )
{
  PrintTabs( m ); // Forward Printing

  if ( m < n )
  {
    indent( m + 1, n );
    PrintTabs( m ); // Backward Printing
  }
}

int main()
{
  indent( 0, MAX );
  return 0;
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜