Pattern Questions ##4

Palakkgoyal
2 min readDec 2, 2022

--

QUESTION1:

16.           1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

SOLUTION:

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

public static void Patterns(int n){
//run the outer loop same as the number of rows
for(int i = 1; i <= n; i++){

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

int c = 1;

for(int k = 1; k <= i; k++){
System.out.print(c + " ");
c = c*(i-k)/k;
}
System.out.println();
}

}

}



QUESTION2:

17.      1
212
32123
4321234
32123
212
1

SOLUTION:

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

public static void Patterns(int n){
//run the outer loop same as the number of rows
//As we want to print numbers, we will start the loop from 1 and
//not from 0
for(int i = 1; i <= 2*n; i++){

int c = i <= n ? i : 2*n-i;

for(int j = 1; j <= n-c; j++){
System.out.print(" ");
}
for(int k = c; k >= 1; k--){
System.out.print(k);
}
for(int l = 2; l <= c; l++){
System.out.print(l);
}

System.out.println();
}

}
}



QUESTION3:

18.   **********
**** ****
*** ***
** **
* *
* *
** **
*** ***
**** ****
**********

SOLUTION:

public class Hello{
public static void main(String[] args) {
Pattern(7);
}

static void Pattern(int n){
//run the outer loop same time as the number of rows
for(int i = 1; i <= 2*n; i++){

int c = i <= n ? n-i : i-n-1;
int s = i <= n ? 2*(i-1) : 2*(2*n-i);

//count the number of column occupied and run the inner loop that much time
for(int j = 1; j <= 2*n; j++){
if(j <= c+1){
System.out.print("*");
}else if(j <= c+1+s){
System.out.print(" ");
}else{
System.out.print("*");
}
}
System.out.println();
}
}
}



QUESTION4:

19.    *        *
** **
*** ***
**** ****
**********
**** ****
*** ***
** **
* *

SOLUTION:

public class Hello{
public static void main(String[] args) {
Pattern(5);
}

static void Pattern(int n){
//run the outer loop same as the number of rows
for(int i = 1; i < 2*n; i++){

int c = i <= n ? i : 2*n-i;
int s = 2*(n-c);

for(int j = 1; j <= 2*n; j++){
if(j <= c){
System.out.print("*");
}else if(j <= c+s){
System.out.print(" ");
}else{
System.out.print("*");
}
}
System.out.println();
}
}
}

QUESTION5:

20.    ****
* *
* *
* *
****

SOLUTION:

public class Hello{
public static void main(String[] args) {
Pattern(5);
}

static void Pattern(int n){
//run the outer loop same as the number of rows
for(int i = 1; i <= n; i++){

for(int j = 1; j < n; j++){
if(i == 1 || i == n || j == 1 || j == n-1){
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}



Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet