Solve Any Pattern Question Using This Trick!




Program:

public class Patterns {
public static void main(String[] args) {
pattern7(4);

}
/*pattern1
*
* *
* * *
* * * *
* 4 rows and 4 column */

static void pattern1(int n) {
for (int i = 1; i <= n; i++) {// i is row
for (int j = 1; j <= i; j++) {// j is row
System.out.print("* ");
}
System.out.println();
}
}

/*pattern2
* * * *
* * * *
* * * *
* * * *
4 rows and 4 column*/
static void pattern2(int n) {
for (int i = 1; i <= n; i++) {// i is row
for (int j = 1; j <= n; j++) {// j is row
System.out.print("* ");
}
System.out.println();
}
}

/*pattern3
* * * *
* * *
* *
*
4 rows and 4 column*/
static void pattern3(int n) {
for (int i = 1; i <= n; i++) {// i is row
for (int j = 1; j <= n - i + 1; j++) {// j is row
System.out.print("* ");
}
System.out.println();
}
}

/*pattern4
1
1 2
1 2 3
1 2 3 4
*/
static void pattern4(int n) {
for (int i = 1; i <= n; i++) {// i is row
for (int j = 1; j <= i; j++) {// j is row
System.out.print(j + " ");
}
//After printing row add new line
System.out.println();
}
}
/*pattern5
*
* *
* * *
* * * *
* * *
* *
4 rows and 4 columns*/

static void pattern5(int n) {
for (int i = 0; i < 2 * n; i++) {
int calumnInRow = i > n ? 2 * n - i : i;
for (int j = 0; j < calumnInRow; j++) {
System.out.print("* ");
}
//After printing row add new line
System.out.println();
}
}

/*pattern6
*
* *
* * *
* * * *
* * *
* *
*
*/
static void pattern6(int n) {
for (int i = 0; i < 2 * n; i++) {
int calumnInRow = i > n ? 2 * n - i : i;
int space = n - calumnInRow;
for (int s = 0; s < space; s++) {
System.out.print(" ");
}
for (int j = 0; j < calumnInRow; j++) {
System.out.print("* ");
}
//After printing row add new line
System.out.println();


}
}
/*pattern7
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
*/
static void pattern7(int n){
for(int i = 1; i <= n;i++){
for(int space = 0;space < n-i;space++){
System.out.print(" ");
}
for(int j = i; j >=1;j--){
System.out.print(j + " ");
}
for(int j = 2; j<=i;j++){
System.out.print(j + " ");
}
System.out.println();
}
}
}


Comments

Popular posts from this blog

Login Page in Java | IntelliJ Idea | Create Login Page

Java Arrays Programs

Java Loops Programs