c# alignment question

  • Thread starter Thread starter Brendan
  • Start date Start date
B

Brendan

Hi I am new to c# and working through a problem in a book:

Design and develop a program that prints the following diamond shape.
You may use output statements that print a single asterisk ( * ), a
single space or a single newline character. Maximize your use of
repetition ( with nested loop structures) and minimize the number of
output statements.

*
***
*****
*******
*********
***********
*********
*******
*****
***
*

Ive got so far;

static void Main(string[] args)
{
int count=0, print=0;

while(count<6)
{
print = count + 1;
while(print>1)
{
printstar();
print--;
}
Console.WriteLine(" ");
count++;
}
while(count>0)
{
print = count + 1;
while(print>1)
{
printstar();
print--;
}
Console.WriteLine(" ");
count--;
}
Console.WriteLine(count);
Console.WriteLine(print);


}

static void printstar()
{
Console.Write("*");
}

which produces the following output -

*
**
***
****
*****
******
*****
****
***
**
*

I am stuck on producing the diamond shape and aligning all the start
centered in the dos console.

Can some please help me with the code or even just the algorithm to
produce it.

Thanks
 
Hello Brendan,

The first line is five spaces, and one star
the second line is four spaces, and three stars
the third line is three spaces, and five stars
....
the sixth line is zero spaces, and eleven stars

(look for the pattern... do you see it? 5,4,3,2,1,0 and 1,3,5,7,9,11 )

So you need to calculate the second pattern from the first.

there's a loop variable (X) going from (5) to (0) increment by (-1)
inside the loop
perform a loop to print a space character X times
perform a loop to print a star character ((5-X) * 2) + 1 times <--
can you come up with a better function than this?
end loop

That will get your top half of the diamond.

Now, if you look at your code, you've hard-coded three values... the (5),
the (0), and the (-1) in the FOR loop statement

Your assignment is to use loops, right. so, how can you use the code you
have in another loop?

Think about it. The pattern that was decending, is now ascending.

so, enclose the entire function in another loop, one that only executes
twice.
The first time through, use 5, 0, and -1 in the embedded FOR statement
The second time, use 1, 5, and 1 in the embedded FOR statement

I hope this helps,
--- Nick
 
Here is one way that uses lots of lovely loops

static void Main(string[] args)
{
for (int i=5; i>= -5; i--)
{
int absVal = Math.Abs(i);

PrintSpace(40);
PrintSpace(absVal);
PrintStar(1 + (5-absVal)*2);
Console.WriteLine();
}
}
static void PrintStar(int count)
{
for (int i=0; i < count; i++)
{
Console.Write("*");
}
}
static void PrintSpace(int count)
{
for (int i=0; i < count; i++)
{
Console.Write(" ");
}
}
 
Back
Top