2

I am coding an Inversed pyramid console application, when you enter a number, For example 3, It'll output it with the number of staircase,

*****
 ***
  *

It works and everything is fine but when it outputs the pyramid. It keeps spamming spaces till the program crashes. Here's the source code: Note: This is a recursion project.

#include <iostream>
using namespace std;

int Pyramid(int n, int index)
{
    if(index > n)  //Base Case
    {
        return 0;
    }
    for(int i=index+1; i<=n; i++)
    {
        cout<<" ";
    }
    for(int j=1; j<index*2; j++)
    {
        cout<<"*";
    }
    cout<<endl;
    return Pyramid(n, index-1);
}

int main()
{
    int n;
    cin>>n;
    Pyramid(n, n);
    return 0;
}

Can anyone help me fix this problem and keep it a recursion project?

L_J
  • 2,351
  • 10
  • 23
  • 28
Abdullah Ahmed
  • 293
  • 2
  • 16
  • 3
    A few sidenotes: **(1)** [Don't use `using namespace std`](https://stackoverflow.com/q/1452721/8746648) **(2)** Indent and format your code properly, or use `clang-format`. – asynts Apr 01 '21 at 09:34
  • 2
    @asynts I am not using any other header file so no need to remove `using namespace std`, For formatting, I'll format my code next time, thanks. – Abdullah Ahmed May 27 '21 at 11:58

2 Answers2

4

Your stop condition in your recursion is wrong. Here is what I did and it displays the star pyramid correctly

int Pyramid(int n, int index)
{
    // your stop condition is wrong (not index>n but index ==0)
    if (index ==0 )
    {
        return 0;
    }
    //until here
    for(int i=index+1; i<=n; i++)
    {
        cout<<" ";
    }
    for(int j=1; j<index*2; j++)
    {
        cout<<"*";
    }
    cout<<endl;
    return Pyramid(n, index-1);
}

An example execution is as follows:

10
*******************
 *****************
  ***************
   *************
    ***********
     *********
      *******
       *****
        ***
         *
Pat. ANDRIA
  • 2,330
  • 1
  • 13
  • 27
4

    if(index > n)  //Base Case
    {
        return 0;
    }

This seems not correct. You start index with n, and index will always be decremented. index > n will never be reached.

dswij
  • 148
  • 6