I want to print pattern like
but i have a problem with output.
my code is:
int i, j, k;
for (i = 5; i >= 1; i--)
{
for (j = 5; j > i; j--)
{
Console.Write(" ");
}
for (k = 1; k < (i * 2); k++)
{
Console.Write("*_");
}
Console.WriteLine();
}
Console.ReadLine();
There are just a couple of issues:
"*_" for every iteration, including the last. Instead, we should only write "*" on every iteration, followed by "_" on every iteration except the last one. We can do this with two different Console.Write calls, where the second one checks to see if our iterator is at the last position.k < (i * 2) (on the first iteration, i == 5, so i * 2 == 10, which means we'll iterate 9 times). We can fix this by changing it to k <= ifor loops. This reduces their scope, which is usually a good thing.For example:
for (int i = 5; i >= 1; i--)
{
for (int j = 5; j > i; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("*");
if (k < i) Console.Write("_");
}
Console.WriteLine();
}
Console.ReadLine();
The code can be simplified a little bit if we use the string constructor that takes in a character and a number of times to repeat it to write our spaces, and if we iterate one less time in our inner loop we can write "*_" followed by a WriteLine("*"):
for (int i = 5; i >= 1; i--)
{
// Write (5 - i) spaces at once
Console.Write(new string(' ', 5 - i));
// Write 'i' count of "*", joined with a "_"
Console.WriteLine(string.Join("_", Enumerable.Repeat("*", i)));
}
Console.ReadLine();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With