Pattern is an arrangement of elements. It may be a mathematical shape like square, rectangle, triangle. These shapes may be printed as hollow pattern, solid pattern or number pattern.
In this blog post, we create three different patterns.
- Solid Square Pattern
- Hollow Rectangle pattern
- Number Triangle pattern
- · This java program uses “#” pattern to print solid square. For printing this pattern, a function “printIt()” is written.
- · This function has two for loops. One for row and another one for column value. Based on the loops, it prints the pattern.
- · In the main function, row and column value is assigned and the printIt() is called using the row and column value.
#Java Program to print Solid square pattern
public class
SquarePattern {
public static void
printIt(int row, int cols) {
for (int i =
0; i < row; i++) {
for (int j
= 0; j < cols; j++) {
System.out.print("# ");
}
System.out.println();
}
}
public static void
main(String[] args) {
int row = 4;
int cols = 4;
printIt(row,
cols);
}
}
·
The output is shown below.
2.How to print hollow rectangle pattern in java:
- · This java program uses “@” pattern to print solid Rectangle. Here,function “printHollow()” holds the code to print the pattern.
- · It uses two for loop to print the pattern.
- · In the main function, row and column value is assigned and the printHollow() is called using the row and column value.
#Java Program to print rectangular hollow pattern
public class RectPattern {
public static void
printHollow(int row, int col) {
for (int I =
0; I < row; i++) {
for (int j
= 0; j < col; j++) {
if (I
== 0 || I == row- 1 || j == 0 || j == col – 1)
{
System.out.print(“@ “);
}
else {
System.out.print(“ “);
}
}
System.out.println();
}
}
public static void
main(String[] args) {
int row = 6;
int col = 4;
printHollow(row, col);
}
}
·
This program gives you the output as shown below
command prompt.
3.How to print Number Triangle pattern in java:
·
This program prints numbers in triangular
pattern.Here, printNumber() is used to print the numbers.
·
It gets the values from main() function.
#Java Program to print Triangle number pattern
public class TriaPattern {
public static void
printNumber(int n) {
for (int i =
1; i <= n; i++) {
for (int j
= 1; j <= n - i; j++) {
System.out.print(" ");
}
for (int j
= 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
public static void
main(String[] args) {
int n = 6;
printNumber(n);
}
}
· Compile
and run the program. The output is displayed here.
These are the ways of creating java programs to print the various patterns. Happy coding!!!!!
No comments:
Post a Comment