Java program to implement patterns

Simple Java program to implement the following pyramid pattern.

1
2 2
3 3 3
4 4 4 4 
 
and
4
3 3
2 2 2
1 1 1 1


Code:



public class pattern{

public static void main(String srgs[]){

System.out.println("first pattern");

int a=4;

for(int i=1;i<=4;i++){

System.out.println(" ");

for(int j=1;j<=i;j++){System.out.print(" " +i);}



}

System.out.println(" ");

System.out.println("Second pattern");



for(int i=4;i>=1;i--){

System.out.println(" ");

for(int j=1;j<=i;j++){System.out.print(" " +i);}



}

}}






Simple Java program to print following Pascal triangle using irregular multi-dimensional array

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1




Code:


public class triangle{



public static void main(String args[]) {

int [][] tri = new int[5][];

for (int r=0; r<tri.length; r++) {

tri[r] = new int[r+1];

tri[r][0] = 1;

tri[r][r] = 1;

for (int c=1; c<r; c++) {

tri[r][c] = tri[r-1][c]+tri[r-1][c-1];

}

}

for (int r=0; r<tri.length; r++) {

for (int c=0; c<tri[r].length; c++) {

System.out.print(" "+tri[r][c]);

}

System.out.println("");

}

}

}





Comments

Popular posts from this blog

C program to evaluate Prefix Expression using Stack data structure

Java Program to Implement sorting algorithm using TCP on Server application

C++ program to perform data transformation Min-max and Z score Normalization