C++ Exercises: Rearrange the elements of a given array of integers in zig-zag fashion way
C++ Array: Exercise-12 with Solution
Write a C++ program to rearrange the elements of a given array of integers in zig-zag fashion way.
Note: The format zig-zag array in form a < b > c < d > e < f.
Sample Solution:
C++ Code :
#include<iostream>
using namespace std;
void zig_zag_array(int nums[], int n)
{
bool ans = true;
for (int i=0; i<=n-2; i++)
{
if (ans)
{
if (nums[i] > nums[i+1])
swap(nums[i], nums[i+1]);
}
else
{
if (nums[i] < nums[i+1])
swap(nums[i], nums[i+1]);
}
ans = !ans;
}
}
int main()
{
int nums[] = {0, 1, 3, 4, 5, 6, 7, 8, 10};
int n = sizeof(nums)/sizeof(nums[0]);
cout << "Original array: ";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";
zig_zag_array(nums, n);
cout << "\nNew array elements: ";
for (int i=0; i < n; i++)
cout << nums[i] <<" ";
return 0;
}
Sample Output:
Original array: 0 1 3 4 5 6 7 8 10 New array elements: 0 3 1 5 4 7 6 10 8
Flowchart:

C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to update every array element by multiplication of next and previous values of a given array of integers.
Next: Write a C++ program to separate even and odd numbers of an array of integers. Put all even numbers first, and then odd numbers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C++ Programming: Tips of the Day
Can I assume (bool)true == (int)1 for any C++ compiler?
According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.
The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.
A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1
Ref: https://bit.ly/3PWhs5N
- Exercises: Weekly Top 12 Most Popular Topics
- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion