Moving Zeros to end in an array
#include <iostream>
void display(int arr[], int n)
{
std::cout << "{ ";
for (int i = 0; i < n; i++)
{
std::cout << arr[i] << ", ";
}
std::cout << " }\n";
}
void moveToEnd(int arr[], int n)
{
int count = 0;
for (int i = 0; i < n; i++)
{
if (arr[i] != 0)
{
std::swap(arr[i], arr[count]);
count++;
}
}
display(arr, n);
}
int main()
{
int arr[] = {1, 2, 0, 12, 0};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << "Size of array = " << n << std::endl;
std::cout << "Before moving all zeros to end" << std::endl;
display(arr, n);
std::cout << "After moving all zeros to end" << std::endl;
moveToEnd(arr, n);
return 0;
}
0 Comments