• 10-16-2010
843
The program accepts two character inputs and construct a diamond out of them in this shape:

Code:

A
ABA
ABBBA
ABBBBBA
ABBBA
ABA
A

I'm working on the first half of the diamond, but I'm having trouble constructing the inner Bs, particularly the double increment in every row.

Code:

#include <stdio.h>

char info (void)
{
char x;

printf("Insert a character: ");
scanf("%c", &x);
getchar();

return x;
}

void diamond (char a, char b)
{
int c1, c2, ch = 0, sp = 4, sp1, sp2;

for (c1 = 0; c1 < 4; c1++, sp--, ch++)
{
for (sp1 = 0; sp1 < sp; sp1++)
{
printf(" ");
}

printf("%c", a);

for (c2 = 0; (c2 < ch) && ((ch - c2) < 5); c2++, ch++)
{
printf("%c", b);
}

if (c1 == 0)
{
printf("\n");
}

else
{
printf("%c\n", a);
}
}
}

int main (void)
{
char a, b;

a = info ();
b = info ();

printf("\n");

diamond(a, b);

printf("%c and %c", a, b);

return 0;

• 10-16-2010
Using an increment counter, why not have one of them go up (and later down), by two instead of by just one?

Keep it simple, and if you use variables with descriptive names, instead of c1, c2, etc., it helps a LOT.

I'd think you'd want to track the number of char's that have been printed, so far in the current row, for sure. Also, the number of rows that have been printed.

The a and b printing is just a logic if() statement, inside the inner loop, based on the above two variables.

I believe it's helpful to break this problem up into two parts - the upper triangle, and then the lower upside down triangle, and use different loops for each one, instead of mashing the logic all together, into one pair of loops.
• 10-16-2010
843
For some reason the loop condition is killing me. I don't know how to get the counter to go down after the loops are finished. When I try to get the loop to stop after the difference between the counter and char reaches a certain point, the loop just goes to infinity.

I know that the difference between c2 and char has to increase, but I don't know how to stop the loop from continuing.

char - c2 = 1
char - c2 = 3
char - c2 = 5
...

For the naming scheme, c1 is the counter for the outer loop and c2 is the counter for the inner loop. I'm not sure how I can be more descriptive.
• 10-16-2010
843
Got it! I have to initialize ch as -1.
• 10-17-2010