user16554867
user16554867

Reputation:

How To Print Triple Triangle Pattern in JAVA?

I just start learning Java and I'm trying to print this pattern in JAVA but my output is not correct as I want.

I want to Print this pattern :

Treat underscores as spaces
1234554321
1234__4321
123____321
12______21
1________1

Here is code :

import java.util.*;


public class Pattern
{
    public static void main(String args[])
    {
        int i, j, k, p, d;
        k = 1;
        p = 5;
        d = 1;
        System.out.println("The pattern");
        for (i = 1; i <= 5; i++)
        {
            for (j = 1; j < p; j++)
                System.out.print(j);

            for (k = 1; k <= d; k++)
                System.out.print(" ");

            for (k = p; k >= 1; k--)
                System.out.print(k);

            System.out.println();

            p = p - 1;
            d = d + 2;
        }
    }
}

Output I'm getting

The pattern
1234 54321
123   4321
12     321
1       21
         1

Upvotes: 0

Views: 176

Answers (1)

Sandrin Joy
Sandrin Joy

Reputation: 1169

Change

System.out.print(""); 

to

System.out.print(" "); 

A space character need to be added in the print statement to get a space in the output.

Also, if you need to get the highest number twice in your output, you need to slightly edit your 2nd for loop from

for(j=1;j<p;j++)

to

for(j=1;j<=p;j++)
   

A less than or equal to sign will do that.

Upvotes: 2

Related Questions