how to draw an inverted triangle after asking the user for the number of rows in c++ usin reursion not for loop as this code

#include<stdio.h>
#include <conio.h>
int main()
{
    int rows,i,j,space;
    printf("Enter number of rows: ");
    scanf("%d",&rows);
    for(i=rows;i>=1;--i)
    {
        for(space=0;space<rows-i;++space)
           printf("  ");
        for(j=i;j<=2*i-1;++j)
          printf("* ");
        for(j=0;j<i-1;++j)
            printf("* ");
        printf("\n");
    }
    getch();
    return 0;
}

Here's one way:

void MakeInvTri(int rows, int spaces = 0)
{
    static const char temp[21] = "* * * * * * * * * * ";
    static const char temp1[21] = "                    ";
    if (spaces == 0)
    {
        rows *= 2;
    }
    if (rows < 0)
    {
        return;
    }
    string output(temp, rows);
    string space(temp1, spaces);
    cout << space << output << '\n';
    MakeInvTri(rows - 2, ++spaces);
}

This will max out at ten rows though. Increasing the 2 constants will allow more rows.

One could always compute the size of temp[] and temp1[] at runtime, malloc() the arrays, and then use memset() to initialize them, resulting in a pretty much infinite triangle size. Of course, you still need to be sure that the initial array sizes are odd, otherwise you miss the pointy bit at the end. Aren't "edge" cases fun! :-)

Yeah, I used const's for brevity, since the focus was to be the actual routine.
Actually the size doesn't matter, the pointy bit is included either way, since the rows variable is initially doubled and the exit condition is below 0 resulting in the extra last row being printed.

I preffer the following alternative that print an inverted trinagle with any specified number of lines:

include <iostream>
void makeInvTri(int rows, int spaces = 0)
{
  if (rows < 0) return;
  int r = rows;
  int s = spaces;
  while(s--) std::cout << " ";
  while(r--) std::cout << "*";
  std::cout << std::endl;
  makeInvTri(rows - 2, ++spaces);
}

void invTri(int rows)
{
  makeInvTri((rows-1)*2+1);
}

int main()
{
  invTri(1); // Here you can specify any number of lines.
}

With this alternative, the triangle always end in only one star.

In the example you obtain an eleven rows triangle:

*********************
 *******************
  *****************
   ***************
    *************
     ***********
      *********
       *******
        *****
         ***
          *
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.