Reputation: 81
here is the (not working code) and it should print the shape below but its not :
static void Main(string[] args)
{
int i = 1;
int k = 5;
int h = 1;
while (i <= 5)
{
Console.WriteLine("");
while (k > i)
{
Console.Write(" ");
k--;
}
while (h <= i)
{
Console.Write("**");
h++;
}
i++;
}
Console.ReadLine();
}
but when I try to do the same using the while statement the shape gets totally messed up.
any help ?
Upvotes: 0
Views: 11257
Reputation: 1837
Actually I've done this via 'for' loop, z is height and x is equal to length of side.
Isosceles triangle (x>z):
public void Print(int x, int z)
{
var peakStart = x;
var peakEnd = x;
for (int i = 0; i < z; i++)
{
for (int j = 0; j < 2 * x + 1; j++)
{
if (peakStart < 1.5 * x && j >= peakStart && j <= peakEnd)
Console.Write("*");
else
Console.Write(" ");
}
peakStart--;
peakEnd++;
Console.WriteLine("");
}
}
Upvotes: 0
Reputation: 15344
I'll not solve for you just will give you hint only: Use 3 loop statements
1. for line change
2. for spaces (reverse loop)
3. for printing * (odd series in this case) i.e. 2n-1
check in third while statement h <= 2*i - 1;
and print only one *
in place of **
Check here: http://ideone.com/xOB2OI
Upvotes: 0
Reputation: 14038
The problem is that i
, k
and h
are initialised before the outermost loop is entered. Within the outer loop k
and h
are altered by the inner loops. On the second execution of the outer loop k
and h
have the same values as were left after running the inner loops previously. As i
increments in the outer loop, the k
loop will not be entered and the h
loop will only run once.
Think about what values h
and k
should have inside the outermost loop on the second execution.
Upvotes: 0
Reputation: 3497
int NumberOfLines = 5;
int count = 1;
while (NumberOfLines-- != 0)
{
int c = count;
while (c-- != 0)
{
Console.Write("*");
}
Console.WriteLine();
count = count + 2;
}
That's it, simplest implementation.
Upvotes: 2
Reputation: 125610
You have to declare k
and h
within the loop:
static void Main(string[] args)
{
int i = 1;
while (i <= 5)
{
int k = 5;
int h = 1;
Console.WriteLine("");
while (k > i)
{
Console.Write(" ");
k--;
}
while (h <= i)
{
Console.Write("**");
h++;
}
i++;
}
Console.ReadLine();
}
With your current solution, after first outer loop iteration, inner loops do nothing.
Upvotes: 2