Write a java program to convert an array into zig-zag fashion using the function
ADVERTISEMENTS
Write a java program to convert an array into a zig-zag fashion using the function. There are you will learn how to print the zig-zag fashion of an array.
Take an example to print zig-zag fashion through a java program:
// Write a java program to convert
// an array into zig-zag fashion
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;
}
}
}
Output
-----enter the size of the array-----
8
-----Enter the 8 elements one by one-----
12
32
45
12
56
32
56
23
-----The zig-zag pattern-----
12, 45, 12, 56, 32, 56, 23, 32,