Examples:
Input:
arr[ ]= {1, 0, 2, 3, 0, 4, 0, 5 }
Output:
arr[ ] = {1,2,3,4,5,0 0,0}
Input:
arr[ ]= {0,10, 9,0, 8,0,7,0, 6}
Output:
arr[ ] = {10,9,8,7,6,0,0,0,0}
#include <iostream>
using namespace std;
// Function to rearrange the arr
void reArrangeArr(int arr[], int n)
{
// set counter to zero
int count = 0;
// place non zero elements first
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i];
// place zeros at last
while (count < n)
arr[count++] = 0;
}
// Function to print the arr
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
// Main function
int main()
{
int arr[100], N;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
reArrangeArr(arr, N);
printArr(arr, N);
return 0;
}
Output:
Enter Number of elements: 8
0 1 0 2 3 0 4 0
1 2 3 4 0 0 0 0
0 Comments