Reputation: 41
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();
Upvotes: 3
Views: 2884
Reputation: 37020
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 <= i
for
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();
Upvotes: 6
Reputation: 39122
So many ways to do this...here's another one using StringBuilder and a slight cheat by getting rid of the last "_" with Trim(). It's written generically to take the desired number of rows:
public static void Main()
{
StarPattern(7);
Console.WriteLine("Press Enter to Quit...");
Console.ReadLine();
}
public static void StarPattern(int numberStarsInTopRow)
{
StringBuilder sb = new StringBuilder();
for(int row=0; row<numberStarsInTopRow; row++)
{
sb.Clear();
sb.Append(new string(' ', row));
for(int stars=0; stars<(numberStarsInTopRow-row); stars++)
{
sb.Append("*_");
}
Console.WriteLine(sb.ToString().TrimEnd('_'));
Console.WriteLine();
}
}
Output:
*_*_*_*_*_*_*
*_*_*_*_*_*
*_*_*_*_*
*_*_*_*
*_*_*
*_*
*
Press Enter to Quit...
Here's a compact version using the trick posted in the comments by LarsTech:
public static void Main()
{
StarPattern(7);
Console.WriteLine("Press Enter to Quit...");
Console.ReadLine();
}
public static void StarPattern(int numberStarsInTopRow)
{
for(int row=0; row<numberStarsInTopRow; row++)
{
Console.WriteLine(new string(' ', row) + String.Join("_", Enumerable.Repeat("*", numberStarsInTopRow - row)) + Environment.NewLine);
}
}
Upvotes: 0