Pattern Questions ##1

Palakkgoyal
2 min readNov 30, 2022

--

QUESTION1:

1.  *****
*****
*****
*****
*****

Solution:

public class Main{
public static void main(String[] args) {
Patterns(5);
}

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

//run the inner loop same as the number of columns
for(int j = 0; j < n; j++){
System.out.print("* ");
}
System.out.println();
}

}
}

QUESTION2:

2.  *
**
***
****
*****

SOLUTION:

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

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

//run the inner loop same as the number of columns
for(int j = 0; j <= i; j++){
System.out.print("* ");
}
System.out.println();
}

}
}

QUESTION3:

3.  *****
****
***
**
*

SOLUTION:

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

public static void Patterns(int n){
//run the outer loop same as the number of rows
for(int i = n; i > 0; i--){
for(int j = 1; j <= i; j++){
System.out.print("* ");
}
System.out.println();
}

}
}

QUESTION4:

4.  1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

SOLUTION:

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

public static void Patterns(int n){
//run the outer loop same as the number of rows
//As we are going to print numbers so start the loop with 1 not with 0
//anotherwise, it'll look messy

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

}
}

QUESTION5:

5.  *
**
***
****
*****
****
***
**
*

SOLUTION:

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

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

//Everything will remain same but the main thing to define is this c
//which will tell how manu columns are going to be printed as the loop runs
int c = i > n ? 2*n - i : i;

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

}
}

Thank you for reading. If you've 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