Reputation: 5
I am trying to get output like
*****
****
***
**
*
But my code is giving the wrong output. My output is:
Please enter the size: 9
*********
********
*******
******
*****
****
***
**
*
and my code is:
#include<iostream>
using namespace std;
int main (void)
{
int row, column, size;
cout << "Please enter the size: ";
cin >> size;
cin.ignore(999,'\n');
for (row = size; row <= size; row--)
{
if (row <= 0)
{
break;
}
else if (row == size)
{
for (column = 1; column <= size; column++)
{
cout << "*";
}
}
else
{
for (column = row; column <= row; column--)
{
if (column <= 0)
{
break;
}
cout << ' ';
}
for (column = row; column <= row; column--)
{
if (column <= 0)
{
break;
}
cout << "*";
}
}
cout << endl;
}
cout << endl;
cout << "Please press enter to finish...";
cin.ignore(999,'\n');
return 0;
}
I don't know what's wrong and where it is but I am thinking the problem might be in the else loop.
Upvotes: 0
Views: 123
Reputation: 2226
What you are doing here is :
*
s for first line (in amount of size)size - loopCounter
spaces then print size - loopCounter
*
sAs you can see this algorithm can't get you the shape you want. Also why you loop backward and check for none negative value? you don't need it. What you actually want is :
The only thing that important here is how to generate data of each row. as you can see the count of spaces in each row is equal to index of column (starting with 0).
Here's what you can try (I broke inner loop into two loops):
#include<iostream>
using namespace std;
int main(void)
{
int size;
cout << "Please enter the size: ";
cin >> size;
cin.ignore(999, '\n');
for(int column = 0; column < size; ++column)
{
for(int spaces = 0; spaces < column; ++spaces)
{
cout << " ";
}
for(int starts = 0; starts < size - column; ++starts)
{
cout << "*";
}
cout << endl;
}
cout << "Please press enter to finish...";
cin.ignore(999, '\n');
return 0;
}
Upvotes: 1
Reputation: 33854
Try to re-think your problem. You have a lot of complex code to achieve something simple. Your output should look like this:
*****
****
***
**
*
So some things to note about this:
So with this your code should be simple:
// PSEUDO CODE
for row = 0 to max_rows
for i = 0 to max_rows
if (i < row)
print a space
else
print a *
And that should do it.
Upvotes: 1