Monday 15 February 2016

Java program which prints the pattern

Write a Java program which prints the following pattern on the console when the input for no. of rows (n=5).


Ans:

public class Test {
    public static void main(String[] args) {
        int rows=5;
        upper(rows);
        lower(rows-1);
    }
    static void upper(int rowCount){
        int starCount=1;
        int spaceCount=rowCount-1;
        for(int i=1;i<=rowCount;i++){
            for(int j=1;j<=spaceCount;j++){
                System.out.print("  ");
            }
            for(int j=1;j<=starCount;j++){
                System.out.print("* ");
            }
            starCount+=2;
            spaceCount--;
            System.out.println();
        }
    }
    static void lower(int rowCount){
        int starCount=rowCount*2-1;
        int spaceCount=1;
        for(int i=1;i<=rowCount;i++){
            for(int j=1;j<=spaceCount;j++){
                System.out.print("  ");
            }
            for(int j=1;j<=starCount;j++){
                System.out.print("* ");
            }
            starCount-=2;
            spaceCount++;
            System.out.println();
        }
    }

}

1 comment:

  1. Good program and nice tutorial blog.

    P.S. You can also visit my programming and tech blog too.

    ReplyDelete