
Difficult Triangles
Hi, I'm fairly new to C and I'm making some triangles. The problem I have is that I need to make this:
Code:
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
Here is the code I've been playing around with:
Code:
for (row = 10; row >= 1; row)
{
for (spaces = 10; spaces <= row; spaces++)
printf(" ");
for (column = 1; column <= (row*21); column++)
printf("*");
printf("\n");
}
I've already been through loads and loads playing with different numbers etc but I can never get it to look like above. What am I supposed to do?
While I'm here, for this triangle:
Code:
*******************
*****************
***************
*************
***********
*********
*******
*****
***
*
I used this code:
Code:
for (row = 1; row <= 10; row++)
{
for (column = 1; column <= (row*21); column++)
printf("*");
printf("\n");
}
Notice I missed out the spaces loop. Is that OK or should I include it (even though it does nothing).
Thanks in advance

For the first case, think of it in terms of the rows. Make that outer loop. Inside, however, you have to consider that a line is made up of a number of spaces and a number of stars. Something of interest: the number of spaces plus the number of stars is going to be the same for each row. ;)
So to print a line you print a number of spaces and a number of stars. This is dependent upon what row you are on. You see to have this idea, but you have complicated your conditions and index numbers. Try to simplify it.

Code:
for (row = 10; row >= 1; row)
{
for (spaces = 18; spaces >= (row*21); spaces)
printf(" ");
for (column = 1; column <= (row*21); column++)
printf("*");
printf("\n");
}
That did it. Is that the best way? I had to count the number of spaces to get 18 which seems a bit odd.

Sometimes there isn't a "best" way. You have to define what you mean. In my own opinion, I think you've complicated the loop variables way too much.
Here's my method:
Code:
#include <stdio.h>
int main(void)
{
int i, j;
for(i=0;i<10;i++)
{
for(j=0;j<19;j++)
{
putchar(j < (i*2) ? ' ' : '*');
}
putchar('\n');
}
return 0;
}