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 TestPattern {
    public static void main(String[] args) {
        int rows=5;
        print(rows);
    }
    static void print(int rowCount){
        int symbolCount=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<=symbolCount;j++){
                if(j%2==0){
                    System.out.print("* ");
                }else{
                    System.out.print(i+" ");
                }
              
            }
            symbolCount+=2;
            spaceCount--;
            System.out.println();
        }
    }  

}

No comments:

Post a Comment