Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# print stars pattern

Tags:

c#

I want to print pattern like

pattern

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();
like image 813
mojsin94 Avatar asked Apr 13 '26 08:04

mojsin94


1 Answers

There are just a couple of issues:

  1. You're writing "*_" 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.
  2. You're iterating twice as many times as you need to when you do 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
  3. As a side note, we can declare our loop variables locally in the 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();
like image 161
Rufus L Avatar answered Apr 14 '26 20:04

Rufus L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!