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 <iostream>
#define N 100
using namespace std;
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]) {
swap(arru[i], arru[i + 1]);
}
}
else {
if (arru[i] < arru[i + 1]) {
swap(arru[i], arru[i + 1]);
}
}
flag = !flag;
}
}
int main() {
int arru[N], x;
// arru - it will store array elements
// x - size of array
cout << "-----enter the size of the array-----\n";
cin >> x;
cout << "-----Enter the " << x << " elements one by one-----\n";
for (int i = 0; i < x; i++) {
cin >> arru[i];
}
// This will change the array position into zig-zag
cout << "\n-----The zig-zag pattern-----\n";
makeZigZag(arru, x);
for (int i = 0; i < x; i++)
cout << arru[i] << ", ";
cout << "\n";
return 0;
}
Output
-----enter the size of the array-----
6
-----Enter the 6 elements one by one-----
32
3
54
3
54
23
-----The zig-zag pattern-----
3, 54, 3, 54, 23, 32,