Skip to content

Instantly share code, notes, and snippets.

@jignesh8992
Last active August 11, 2022 03:19
Show Gist options
  • Select an option

  • Save jignesh8992/a9e98f2eadbad44c0dbbc3ae84c68dae to your computer and use it in GitHub Desktop.

Select an option

Save jignesh8992/a9e98f2eadbad44c0dbbc3ae84c68dae to your computer and use it in GitHub Desktop.
Patterns Logic Problem Solving
public class Pattern {
public static void main(String[] args){
System.out.print("\nJdroid World\n\n");
patter5(5);
System.out.print("\n\n");
}
/**
*****
*****
*****
*****
*****
*/
public static void patter1(int n){
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
System.out.print("*");
}
System.out.print("\n");
}
}
/**
*
**
***
****
*****
Note: The outer loop which represent row must be same as a total number of row and inner loop which represent column
must be same as number of row in each row
*/
public static void patter2(int n){
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) {
System.out.print("*");
}
System.out.print("\n");
}
}
/**
*****
****
***
**
*
*/
public static void patter3(int n){
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= (n-row+1); col++) {
System.out.print("*");
}
System.out.print("\n");
}
}
/**
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
*/
public static void patter4(int n){
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) {
System.out.print(col+" ");
}
System.out.print("\n");
}
}
/**
*
**
***
****
*****
****
***
**
*
*/
public static void patter5(int n){
for (int row = 1; row <= n*2; row++) {
int columnToBePrint = (row<=n) ? row :(n - (row-n)) ;
for (int col = 1; col <= columnToBePrint; col++) {
System.out.print("*");
}
System.out.print("\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment