going for infinite loop. not able to find the error.

405 views
Skip to first unread message

muhammed sahil

unread,
Nov 16, 2021, 1:58:40 AM11/16/21
to C++ GCU Forum
// to print a star pyramid. there are some errors. can someone help me find the error

#include <iostream> using namespace std; int main() { for (int i=0; i < 5; i++) //0,1,2,3,4 { for (int j = 0; j < 4 - i; j++) //for the spaces. { cout <<" "; } if (i == 0 || i == 4) { for (int p = 0; p < i+1 ; p++) //printing the stars. cout << "*" ; } else { for (int m = 0; m < 2; m++) //inner stars { cout << "*"; for (int k = 0; k < (2*i) - 1 ;k++ ) //inner spaces { cout << " "; } } } cout << endl; } return 0; }

 needed output :

Screenshot 2021-11-16 122623.png

Raptor

unread,
May 24, 2022, 10:35:17 AM5/24/22
to C++ GCU Forum
There are 2 errors.
1. for (int j = 0; j < 4 - i; j++) //for the spaces.
     You have initialised (lack of initialisation rather) the number of rows to 5 in the first for() loop.
      So, you should be checking for j<5-i in the second for loop too.
2.  for (int p = 0; p < i+1 ; p++) //printing the stars.
      The condition is wrong here especially for the last row, since you have to print twice the number of rows + 1.
       The condition should be for (int p = 0; p < (i*2+1) ; p++)

The reformatted code should something like this:
#include <iostream>

using namespace std;

int main()
{
    int n = 5;                  // Initialise the number of rows at the start or get it as an user input.
    for (int i=0; i < n; i++)   //0,1,2,3,4
    {
        for (int j = 0; j < (n-i); j++)       //for the spaces.
        {
            cout <<" ";
        }
        if (i == 0 || i == (n-1))
        {
            for (int p = 0; p < (i*2+1) ; p++) //Print Stars: Condition corrected.
                    cout << "*" ;
        }
        else
        {
             for (int m = 0; m < 2; m++)    //inner stars
             {
                cout << "*";
                for (int k = 0; k < (2*i) - 1 ;k++ )    //inner spaces
                    {
                        cout << " ";
                    }
             }
        }
     cout << endl;
    }
    return 0;
}

This will yield output: (since n = 5)
pyramidStars.PNG
Reply all
Reply to author
Forward
0 new messages