Why my C++ Recursion Program keeps on forever

Viewed 130

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?

2 Answers

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
*******************
 *****************
  ***************
   *************
    ***********
     *********
      *******
       *****
        ***
         *

    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.

Related