Home > database >  How to output this figure using recursion
How to output this figure using recursion

Time:10-29

The number n is entered from the keyboard (in this case, n = 7), you need to output such a figure

How to beautifully combine these 2 functions into one?

static void printD(int N, int k)
{
    for (int i = 1; i <= k / 2; i  )
        Console.Write(" ");

    for (int i = 1; i <= N - k   1; i  )
        Console.Write("*");

    Console.WriteLine();

    if (k < N)
        printD(N, k   2);
}

static void printU(int N, int k)
{
    for (int c = 1; c <= N / 2   1 - k; c  )
        Console.Write(" ");

    for (int c = 1; c <= k * 2 - 1; c  )
        Console.Write("*");

    Console.WriteLine();

    if (k < N / 2   1)
        printD(N, k   1);
}

enter image description here

CodePudding user response:

I suggest extracting a method which prints a single line:

static bool printLine(int N, int k) {
  if (k <= 0 || k > N)
    return false;
    
  Console.Write(new string(' ', (N - k) / 2));
  Console.Write(new string('*', k));
    
  return true;  
}

Then we can easily implement recursive printing for down and up triangles:

static void printD(int N, int k) {
  if (printLine(N, k)) {
    Console.WriteLine();
    printD(N, k - 2);
  }       
}

static void printU(int N, int k) {
  if (printLine(N, k)) {
    Console.WriteLine();
    printU(N, k   2);
  }      
}

Finally, to draw a diamond shape figure we have to print up and then down triangles. So in order to combine triangles all we have to do is to call printU and printD:

static void print(int N) {
  printU(N, N % 2 == 0 ? 2 : 1);
  printD(N, N);
}

Demo:

print(6);
Console.WriteLine();
print(5);

Outcome:

  **
 ****
******
******
 ****
  **

  *
 ***
*****
*****
 ***
  *

Please, fiddle with the code.

  • Related