Home > Back-end >  Right-angled triangle pattern with recursion numbers C
Right-angled triangle pattern with recursion numbers C

Time:12-30

I'm trying to print a right angled triangle with ascending and descending numbers using recursion only.

void straightTriangular(int num)
{
    if (num == 0)
    {
        return;
    }

    straightTriangular(num - 1);

    for (int i = 1; i <= num; i  )
    {
        cout << i;
    }
    cout << endl;
}

How can I do this with recursion only without "for" loop?

if the user input number is 4 then I want the output to be this:

1
121
12321
1234321

my output using the code I posted:

1
12
123
1234

CodePudding user response:

Notice that a triangle(n) has a triangle(n-1) on top of it. It has self-similar structure above it.

Also notice that a layer looking like x...n...x is x (x 1)...n...(x 1) x, which has self-similar structure inside it.

void layer(int x, int n) {
    std::cout << x;
    if (x >= n) return;
    layer(x   1, n);
    std::cout << x;
}

void triangle(int n) {
    if (n <= 0) return;
    triangle(n - 1);
    layer(1, n);
    std::cout << std::endl;
}

If you want to render a pyramid with each layer centered, instead of a right-angled triangle, then what appears above a layer is not just a simple triangle, but an indented triangle. You must keep track of this indentation.

The layer function remains the same, but you first print out some space according to the indentation level of the current pyramid.

#include <iostream>

void space(int n) {
    if (n <= 0) return;
    std::cout << ' ';
    space(n-1);
}

void layer(int x, int n) {
    std::cout << x;
    if (x >= n) return;
    layer(x   1, n);
    std::cout << x;
}

void pyramid(int n, int indent) {
    if (n <= 0) return;
    pyramid(n - 1, indent   1);
    space(indent);
    layer(1, n);
    std::cout << std::endl;
}

int main() {
    pyramid(4, 0);
}

CodePudding user response:

You can have:

  • a printTriangleRec function that goes on printing every line recursively,
  • two printAscendingRec and printDescendingRec functions that print the two halves of each line recursively.

[Demo]

#include <iostream>  // cout

void printAscendingRec(int cur, int top)
{
    std::cout << cur;
    if (cur != top)
    {
        printAscendingRec(cur   1, top);
    }
}

void printDescendingRec(int cur)
{
    if (cur)
    {
        std::cout << cur;
        printDescendingRec(cur - 1);
    }
}

void printTriangleRec(int cur, int top)
{
    printAscendingRec(1, cur);
    printDescendingRec(cur - 1);
    std::cout << "\n";
    if (cur != top)
    {
        printTriangleRec(cur   1, top);
    }
}

void printTriangle(int num)
{
    if (num < 1)
    {
        std::cout << "Error: num < 1\n";
        return;
    }
    printTriangleRec(1, num);
}

int main()
{
    printTriangle(4);
}
  •  Tags:  
  • c
  • Related