How to write a program in Java to display the following Patterns
#
* *
# # #
* * * *
# # # # #
Answers
Answer:
Star Patterns in Java
First, let us begin with the basic and the commonly asked pattern program in Java i.e Pyramid.
1. Pyramid Program
*
* *
* * *
* * * *
* * * * *
Let’s write the java code to understand this pattern better.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Edureka
{
public static void pyramidPattern(int n)
{
for (int i=0; i<n; i++) //outer loop for number of rows(n) { for (int j=n-i; j>1; j--) //inner loop for spaces
{
System.out.print(" "); //print space
}
for (int j=0; j<=i; j++ ) //inner loop for number of columns
{
System.out.print("* "); //print star
}
System.out.println(); //ending line after each row
}
}
public static void main(String args[]) //driver function
{
int n = 5;
pyramidPattern(n);
}
}
2. Right Triangle Star Pattern
*
* *
* * *
* * * *
* * * * *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Edureka
{
public static void rightTriangle(int n)
{
int i, j;
for(i=0; i<n; i++) //outer loop for number of rows(n) { for(j=2*(n-i); j>=0; j--) // inner loop for spaces
{
System.out.print(" "); // printing space
}
for(j=0; j<=i; j++) // inner loop for columns
{
System.out.print("* "); // print star
}
System.out.println(); // ending line after each row
}
}
public static void main(String args[])
{
int n = 5;
rightTriangle(n);
}
}
3. Left Triangle Star Pattern
*
* *
* * *
* * * *
* * * * *
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Edureka
{
public static void printStars(int n)
{
int i, j;
for(i=0; i<n; i++) //outer loop for number of rows(n) { for(j=2*(n-i); j>=0; j--) // inner loop for spaces
{
System.out.print(" "); // printing space
}
for(j=0; j<=i; j++) // inner loop for columns
{
System.out.print("* "); // print star
}
System.out.println(); // ending line after each row
}
}
public static void main(String args[])
{
int n = 5;
printStars(n);
}
}
4. Diamond Shape Pattern Program in Java
Enter the number of rows: 5
*
***
*****
*******
*********
*******
*****
***
*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.Scanner;
public class Edureka
{
public static void main(String args[])
{
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n - 1;
for (j = 1; j<= n; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
space = 1;
for (j = 1; j<= n - 1; j++)
{
for (i = 1; i<= space; i++)
{
System.out.print(" ");
}
space++;
for (i = 1; i<= 2 * (n - j) - 1; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
}