Convert an Array into Zig Zag in C language using Function
ADVERTISEMENTS
Convert an array into zig zag in c language using function. In this article, you will learn how to convert an array into zig zag in c language using function.
Source Code
// Convert an Array into Zig Zag in C language using Function
#include <stdio.h>
#include <stdbool.h>
#define N 100
// `stdbool.h` header file loaded to call the boolean data type
void makeZigZag(int arru[], int n) {
bool flag = true;
int temp;
for (int i = 0; i <= n - 2; i++) {
if (flag) {
if (arru[i] > arru[i + 1]) {
temp = arru[i];
arru[i] = arru[i + 1];
arru[i + 1] = temp;
}
}
else {
if (arru[i] < arru[i + 1]) {
temp = arru[i];
arru[i] = arru[i + 1];
arru[i + 1] = temp;
}
}
flag = !flag;
}
}
int main() {
int arru[N], x;
// arru - it will store array elements
// x - size of array
printf("-----enter the size of the array-----\n");
scanf("%d", &x);
printf("-----Enter the %d elements one by one-----\n", x);
for (int i = 0; i < x; i++) {
scanf("%d", &arru[i]);
}
// This will change the array position into zig-zag
printf("\n-----The zig-zag pattern-----\n");
makeZigZag(arru, x);
for (int i = 0; i < x; i++)
printf("%d, ", arru[i]);
printf("\n");
return 0;
}
Output
-----enter the size of the array-----
8
-----Enter the 8 elements one by one-----
23
54
12
65
87
44
45
23
-----The zig-zag pattern-----
23, 54, 12, 87, 44, 65, 23, 45,