Left Arrow Pattern and Right Arrow Pattern in Java using Function
Left arrow pattern and right arrow pattern in java using function. In this article, you will learn how to print the left arrow pattern and right arrow pattern in java using the function.
You should have the knowledge of the following topics in java programming to understand this program.
- Java
java.util.Scanner
package - Java
main()
method - Java
System.out.println()
method - Java
System.out.print()
method
In this program, we are using java.util.Scanner
package to take the user's input from the console.
Source Code
// Left Arrow Pattern and Right Arrow Pattern in Java using Function
import java.util.Scanner;
public class Main {
// It's the driver method
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Main main = new Main();
int rows;
System.out.println("-----Enter the number of rows to print the left & right arrows pattern-----");
rows = in.nextInt();
if (rows > 0) {
// calling function to print the pattern
main.leftRightArrowsPattern(rows);
}
}
// It will print left arrow pattern and right arrow pattern
int leftRightArrowsPattern(int rows) {
int r, r1, c, row1;
row1 = rows;
rows = rows * 4;
System.out.println("\n----Ths is the left arrow pattern-----\n");
for (r = 1; r < rows; r++) {
// To print the left arrow
if (r <= row1) {
for (c = 1; c <= (row1 - r); c++)
System.out.print(" ");
for (c = r;c <= row1; c++)
System.out.print("*");
System.out.print("\n");
}
if (r > row1 && r <= row1 * 2) {
for (c = 1; c <= (r - row1); c++)
System.out.print(" ");
for (c = 1; c <= (r - (row1 - 1)); c++) {
if ((r - row1) < row1)
System.out.print("*");
}
System.out.print("\n");
}
// To print the right arrow
if (r > row1 * 2 && r <= row1 * 3) {
if (r == (row1 * 2) + 1)
System.out.println("\n----Ths is the right arrow pattern-----\n");
for (c = (r - 1) - (row1 * 2); c >= 1; c--)
System.out.print(" ");
for (c = (3 * row1) - (r - 1); c >= 1; c--)
System.out.print("*");
System.out.print("\n");
}
if (r > row1 * 3) {
for (c = (row1 * 4) - (r + 1); c >= 1; c--)
System.out.print(" ");
for (c = (r + 1) - (3 * row1); c >= 1; c--)
System.out.print("*");
System.out.print("\n");
}
}
return 0;
}
}
Output
-----Enter the number of rows to print the left & right arrows pattern-----
6
----Ths is the left arrow pattern-----
******
*****
****
***
**
*
**
***
****
*****
******
----Ths is the right arrow pattern-----
******
*****
****
***
**
*
**
***
****
*****
******
Explanation
In this program, we have taken the size of the pattern 6
from the user then It will print the left & right arrows pattern.