Java Online Compiler
Example: Print Spiral Pattern in Java language
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Print Spiral Pattern in Java language import java.util.Scanner; public class Main { public static int R = 3; public static int C = 6; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[][] arru = { { 31, 32, 33, 34, 35, 36 }, { 47, 48, 49, 40, 41, 42 }, { 53, 54, 55, 56, 57, 58 } }; System.out.println("-----The spiral pattern is-----"); // This will print the spiral pattern spiralPrint(R, C, arru); System.out.print("\n"); } public static void spiralPrint(int m, int n, int[][] arru) { int i, k = 0, l = 0; // k - starting row index // m - ending row index // l - starting column index // n - ending column index // i - iterator while (k < m && l < n) { // This will print the first row from the remaining rows for (i = l; i < n; ++i) { System.out.print(arru[k][i] + ", "); } k++; // This will print the last column from the remaining columns for (i = k; i < m; ++i) { System.out.print(arru[i][n - 1] + ", "); } n--; // This will print the last row from the remaining rows if (k < m) { for (i = n - 1; i >= l; --i) { System.out.print(arru[m - 1][i] + ", "); } m--; } // This will print the first column from the remaining columns if (l < n) { for (i = m - 1; i >= k; --i) { System.out.print(arru[i][l] + ", "); } l++; } } } }
Output
Clear
ADVERTISEMENTS