Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Right-angled triangle pattern with recursion numbers C++

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1
121
12321
1234321

my output using the code I posted:

1
12
123
1234

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading