Fritz
Fritz

Reputation: 11

Java program putting 2 char and space in pyramid pattern

I tried making a java program using 2 char with a space in pyramid pattern. I'm stuck halfway because i want to display the variable b but i dont know where to put and the result is it always display 1 char only. This is only for references for my upcoming exams. Little help is much appreciated.

Here's my code:

public static void main (String[]args){
   Scanner in =new Scanner(System.in);

   int rows;
   char a, b;

   System.out.print("Enter how many rows");
   rows = in.nextInt();
   System.out.print("Enter 1st char");
   a=in.next().charAt(0);
   System.out.print("Enter 2nd char");
   b=in.next().charAt(0);

   for (int r=2;r<=rows;r++)
   {
      for (int c=1;c<=r;c++) 
      {
         if (c==r)
         {
         System.out.print(a);
         }
         else
         {
         System.out.print(" ");
         }
      }
      System.out.println();
  }

}

The Output i want to display should be like this:

 *

   #

      *

        #

           *

And so on....

Thanks in advance guys. Badly need it because i didn't quite understand.

Upvotes: 1

Views: 212

Answers (1)

David S.
David S.

Reputation: 292

Use this in your loop

        if (c == r) {
          if (r % 2 == 0)
            System.out.print(a);
          else
            System.out.print(b);
        }

instead of

         if (c==r)
         {
         System.out.print(a);
         }

Simple math - you want every even row to be a and every odd row to be b, so you just check if row is odd or even.

And change

for (int r = 2; r <= rows; r++) 

to

for (int r = 1; r <= rows; r++) 

Output from my snippet:

Enter how many rows5
Enter 1st char*
Enter 2nd char#
#
 *
  #
   *
    #

Upvotes: 4

Related Questions