triangle pattern centered
i want to create a pattern in c++ that looks like a trianlge(or half a diamond) using asteriscks: the pattern should have 1, 2, 3, 4, and end in 5 stars like this
*
**
***
****
*****
(but straight!) my code is as follows:
-`#include using namespace std; int main() {
int size;
cout<<"size:"<<endl;
cin>>size;
int blank=size/2;
int newsize=1;
for (int i=0; i<=size/2; i++)
{
for(int j=blank;j>0;j--)
cout <<" ";
blank--;
for(int j=newsize; j>0; j--)
cout <<"*";
newsize+=2;
cout <<endl;
}
return 0;
} ` my only problem with it is that it开发者_开发技巧 displays 1, 3,and 5 stars like this.
*
***
*****
its just a minor problem but although i have changed different parts of the code i dont seem to get it right.
any suggestions?
thanks :)
I'm not sure what you mean by "but straight", so I'll just ignore that for now...
Start with blank
the same value as size
, so that you can decrement the value each time without having to decrement by a half:
int blank=size;
Loop up to size
instead of size/2
to get more lines:
for (int i=0; i<=size; i++)
Decrement by two in the loop for spaces to get half the number of spaces:
for(int j=blank;j>0;j-=2)
Increase the size by one instead of two to get the slower increase:
newsize++;
That should produce the output that you showed.
Edit:
I tested this to be sure, and the output is:
*
**
***
****
*****
******
To get the exact output that you asked for, start with blank one less:
int blank=size - 1;
Did I get it right: you want to place some asterisks on borders of character places? If so, it isn't possible. Every asterisk (or any other symbol), when displayed in monospace fonts, will reside in a middle of a character place, like in a grid. You can place asterisks inside the cells, but you cannot place asterisks on the borders of the grid.
int NUMLINES = 5;
void display(int, char);
void main(){
for (int i=1; i<= NUMLINES; ++i){
display((NUMLINES + 1 - i), ' ');
display(( 2 * i - 1 ), '*');
cout << endl;
}
}
void display (int howmany, char symbol){
for (int i = 1; i<=howmany; ++i)
cout << symbol;
}
精彩评论