Java Online Compiler
Example: Convert Array into Zig-Zag Fashion in Java language
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Convert Array into Zig-Zag Fashion in Java language import java.util.Scanner; public class Main { public static int i = 1, r = 1; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] arru; int x = 0; // arru - it will store array elements // x - size of array System.out.print("-----enter the size of the array-----\n"); x = in .nextInt(); // mapping size of the array arru = new int[x]; System.out.print("-----Enter the " + x + " elements one by one-----\n"); for (int i = 0; i < x; i++) { arru[i] = in .nextInt(); } // This will change the array position into zig-zag System.out.print("\n-----The zig-zag pattern-----\n"); makeZigZag(arru, x); for (int i = 0; i < x; i++) System.out.print(arru[i] + ", "); System.out.print("\n"); } // It's the function to generate the zig-zag pattern public static void makeZigZag(int arru[], int n) { boolean flag = true; int temp; for (int i = 0; i <= n - 2; i++) { if (flag) { if (arru[i] > arru[i + 1]) { // It will swap the values temp = arru[i]; arru[i] = arru[i + 1]; arru[i + 1] = temp; } } else { if (arru[i] < arru[i + 1]) { // It will swap the values temp = arru[i]; arru[i] = arru[i + 1]; arru[i + 1] = temp; } } flag = !flag; } } }
8 12 32 45 12 56 32 56 23
Output
Clear
ADVERTISEMENTS