I am practicing to generate the star in the following result, but I was fail.
1.
*****
****
***
**
*
2.
*
**
***
****
*****
For my logic on this case, I am thinking that could be generated by using width alignment control on the loop, but the result shown that it is wrong...
* * * * *
* * * *
* * *
* *
*
With the code:
int i,j;
char ch='*';//created for using of alignment
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("%5c", ch);
}
printf("\n");
}
For my logic, I assume that could be generated by using the method of alignment (%5c). However, the result is not as same as what I expected.
I have already succeeded to generate the star as shown as below:
*****
****
***
**
*
With Code:
int i,j;
for(i=1;i<=5;i++)
{
for(j=5;j>=i;j--)
{
printf("*");
}
printf("\n");
}
Do I have the wrong thinking on the method to make pattern 1 and 2? Or the right thinking with the wrong coding?
To align, you might be actually drawing a rectangle. In each row, you output a series of asterisks (possibly empty, i.e., zero asterisks) and a series of spaces (possibly empty, i.e., no spaces).
It is an ideal application of the (condition) ? (value_if_true) : (value_if_false) construct. You always draw the full rectangle, and pattern only changes due to condition: "is this a space or an asterisk?"
int i, j;
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
// This generates a full rectangle
// printf("%c", '*');
// This generates an empty rectangle ;-)
// printf("%c", ' ');
// This generates a triangle
printf("%c", (i >= j) ? '*' : ' ');
}
printf("\n");
}
There are two triangles oriented top-down governed by the condition (i >= j) or (i <= j); to flip the triangles horizontally you replace the increasing sequence with a decreasing sequence, i.e., (6-j) instead of (j):
when j is 6-j is
1 5
2 4
... ...
5 1
so that the test is ((6-j) <= i).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With