Pred Ubsud
Pred Ubsud

Reputation: 33

How can I print the following pattern with the for statement?

How can I print the following pattern with the for statement?

AAAA
AAAB
AABB
ABBB
BBBB

What I tried to do:

Code:

 int stars = 4;
 for (int row = stars; row >= 1; row--)
        {
            for (int i = 0; i < row; i++)
            {
                Console.Write("A");
            }
            Console.WriteLine();
            
        }

Upvotes: 1

Views: 55

Answers (1)

Mark Baijens
Mark Baijens

Reputation: 13222

You where almost there.

  1. I made a small change in the first for loop to add another row (>= 1 to >= 0). We need 5 rows for 4 stars, 6 rows for 5 stars, etc.
  2. Compared the second for loop to stars as well because we want 4 values on each row (when stars is 4).
  3. Added an if statement to check if we need to write an A or B based on the iteration number of both loops.

See code below:

int stars = 4;
for(int i = stars; i >= 0; i--) {
    for(int j = 0; j < stars; j++) {
        if(i > j) {
            Console.Write('A');
        }
        else {
            Console.Write('B');
        }
    }
    Console.WriteLine();               
}

Upvotes: 3

Related Questions