- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert array into Zig-Zag fashion in C++
In this tutorial, we will be discussing a program to convert an array into zig-zag fashion.
For this we will be provided with an array containing distinct elements. Our task is to rearrange the elements of the given array in a zig zag fashion with greater and smaller elements alternatively as compared to the previous element.
Example
#include <iostream> using namespace std; //converting into zig-zag fashion void convert_zigzag(int arr[], int n) { //flag denotes the greater or smaller relation bool flag = true; for (int i=0; i<=n-2; i++) { if (flag) { if (arr[i] > arr[i+1]) swap(arr[i], arr[i+1]); } else { if (arr[i] < arr[i+1]) swap(arr[i], arr[i+1]); } flag = !flag; } } int main() { int arr[] = {4, 3, 7, 8, 6, 2, 1}; int n = sizeof(arr)/sizeof(arr[0]); convert_zigzag(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; }
Output
3 7 4 8 2 6 1
- Related Articles
- Print matrix in zag-zag fashion in C Programming.
- Program to convert linked list to zig-zag binary tree in Python
- Zig-Zag pattern in strings in JavaScript?
- Print Concatenation of Zig-Zag String in n Rows in C++
- Zig Zag Level order traversal of a tree using single queue in C++
- How to create a responsive zig zag (alternating) layout with CSS?
- How to convert a 2D array into 1D array in C#?
- How to convert a tuple into an array in C#?
- Convert array into array of subarrays - JavaScript
- How to convert an array of characters into a string in C#?
- How do you convert a list collection into an array in C#?
- Convert JSON array into normal json in JavaScript
- Java Program to Convert Collection into Array
- Java Program to Convert Array into Collection
- Convert JS array into an object - JavaScript

Advertisements