Welcome to ICSE Java Answers. Ask any questions you have related to Java and we will answer them.
Java is a registered trademark of Oracle. This site is in no way related to or endorsed by Oracle.

Print pattern 1 12 123 1234 12345 1234 123 12 1

0 votes
Write a program to print the following pattern   

            1

         1 2

      1 2 3

   1 2 3 4

1 2 3 4 5

   1 2 3 4

      1 2 3

         1 2

            1
asked by YASH
edited by Ranjith

2 Answers

0 votes

As shown in the diagram below, the pattern can be split into two halves.

For the upper half of the pattern,

  • There are n lines ranging from i = 1 to i = n
  • For line i, print n - i spaces followed by numbers from i to i

For the lower half of the pattern,

  • There are n - 1 lines ranging from i = n - 1 to i = 1
  • For line i, print n - i spaces followed by numbers from i to i

Following is the program

import java.util.Scanner;

public class Pattern {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = scanner.nextInt();

        // Upper half
        for (int i = 1; i <= n; i++) {
            // Print spaces
            for (int j = 1; j <= n - i; j++) {
                System.out.print("  ");
            }
            // Print numbers
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }

        // Lower half
        for (int i = n - 1; i >= 1; i--) {
            // Print spaces
            for (int j = 1; j <= n - i; j++) {
                System.out.print("  ");
            }
            // Print numbers
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

Sample output

Enter n: 5
        1 
      1 2 
    1 2 3 
  1 2 3 4 
1 2 3 4 5 
  1 2 3 4 
    1 2 3 
      1 2 
        1 

 

answered by Ranjith (2,683 points)
0 votes
public class pattern2
{
    public static void main(String args[])
    {
        for(int i=1;i<=5;i++)
        {
            for(int j=4;j>=i;j--)
            {
                System.out.print(" ");
            }
            for(int k=1;k<=i;k++)
            {
                System.out.print(k);
            }
            System.out.println();
        }
        for(int i=4;i>0;i--)
        {
            for(int j=4;j>=i;j--)
            {
                System.out.print(" ");
            }
            for(int k=1;k<=i;k++)
            {
                System.out.print(k);
            }
            System.out.println();
        }
    }
}
answered by dipesh (83 points)
...