I started studying C# and I encountered a problem with one of my assignments. The assignment is to create a pyramid made of stars. The height is designated by user input.
For some reason my first for
loop skips to the end. While debugging, I noticed that the variable height
receives bar
's value, but after that it skips to the end. I have no clue why, as the code seems fine to me.
The do
-while
loop is there to ask the user for a new value, in case the value entered is 0
or lower.
using System;
namespace Viope
{
class Vioppe
{
static void Main()
{
int bar;
do
{
Console.Write("Anna korkeus: ");
string foo = Console.ReadLine();
bar = int.Parse(foo);
}
while (bar <= 0);
for (int height = bar; height == 0; height--)
{
for (int spaces = height; spaces == height - 1; spaces--)
{
Console.Write(" ");
}
for (int stars = 1; stars >= height; stars = stars * 2 - 1)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
}
The condition in a for
loop is the condition which has to keep being true in order to go into the loop body. So this:
for (int height = bar; height == 0; height--)
should be:
for (int height = bar; height >= 0; height--)
Otherwise, the assignment is performed, then it will check whether height
is 0, and if it's not (which is bound to be the case), that's the end of the loop.
See the MSDN documentation for for
loops for more information.
See more on this question at Stackoverflow