Reputation: 624
I'm trying to print this pattern in C:
*
* *
* * *
* * * *
I came up with a similar thing, but it is not perfectly aligned, see this:
*
* *
* * *
* * * *
* * * * *
It's a bit inclined to the right. I think I got the concept right about spacing the stars, but something is wrong, could someone help me fix this?
Here's my code:
#include <stdio.h>
int main() {
int sp, st, i, j, k;
printf("Enter rows: ");
scanf("%d", &st);
sp = st * 2;
for(i = 1; i <= st; i++)
{
for(j = 1; j <= i; j++)
{
if(j == 1)
for(k = 1; k <= sp - i*2; k++)
printf(" ");
printf(" * ");
}
printf("\n");
}
}
Please note, sp = number of spaces, st = number of stars in the last row
Upvotes: 1
Views: 10896
Reputation: 21
This works exactly:
void main()
{
int i = 0, j = 0, k;
for (i = 0; i < 17; i++)
{
for (k = 16; k >= i; k--)
{
printf(" ");
}
for (j = 0; j <= (i); j++)
{
printf("* ");
}
printf("\n");
}
getch();
}
Upvotes: 2
Reputation: 8866
printf(" * ");
You should only print one space in this, probably "* "
for(k = 1; k <= sp - i*2; k++)
Change this to k < sp - i*2;
since you're printing one too many spaces in the beginning.
Also, this isn't technically wrong, but I think you should pull your third for loop (the one with k
) out of your second for loop. You don't really need to do that check on every iteration of the second for loop, since it's just supposed to print the initial spaces.
Upvotes: 3