Displaying Patterns

05 November 2011
Write a method to display a patter as follow:
1
            2 1
          3 2 1
...
n n-1 ... 3 2 1

The method header is

public static void displayPattern(int n)


Input:
9

Output:
1
       21
      321
     4321
    54321
   654321
  7654321
 87654321
987654321

Main.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package displayingpatterns;

import java.util.Scanner;

/**
 *
 * @author dekwan
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        // TODO code application logic here
        Scanner scan = new Scanner(System.in);

        displayPattern(scan.nextInt());
    }

    public static void displayPattern(int n)
    {
        for (int i = 1; i <= n; i++)
        {
            for (int j = n; j > i; j--)
            {
                sop(" ");
            }

            for (int j = i; j > 0; j--)
            {
                sop("" + j);
            }

            sop("\n");
        }
    }

    public static void sop(String str)
    {
        System.out.print(str);
    }

}


0 comments:

Catat Ulasan

Terima kasih kerana memberi ulasan...