We are provided an array and our task is to remove leading zeros from the given array and then print the array.
Input : arr[] = {0, 0, 0, 1, 2, 3} Output : 1 2 3 Input : arr[] = {0, 0, 0, 1, 0, 2, 3} Output : 1 0 2 3
We can create a new array that does not contain the leading zeros of the previous array in the given problem.
In this method we will iterate through the array and insert all numbers except leading zeros.
#include <iostream> using namespace std; int main() { int arr[] = {0, 0, 0, 1, 2, 0, 4}; int n = sizeof(arr) / sizeof(int); // size of given array. int last = -1; for(int i = 0; i < n; i++) { // finding the first non zero element if(arr[i] != 0) { last = i; break; } } if(last == -1) cout << "Empty\n"; else { int b[n - last]; // the new array. for(int i = last; i < n; i++) // inserting the elements in the new array b[i-last] = arr[i]; for(int i = 0; i < n-last; i++) // printing the array cout << b[i] << " "; } }
1 2 0 4
In the given program, we first iterate through the array arr and find the first non The index of the zero element, which is stored in a variable named last. If last is -1 after traversing, it means that the entire array consists of zeros, so we print "Empty".
Now that we have the index of the first non-zero element, we can determine the size of the new array, which is (n - last), and then we run a for loop starting from last to n-1. We insert these elements into the new array and print the new array.
In this article, we solved the problem of removing leading zeros from an array. We also learned a C program to solve this problem and the complete solution. We can write the same program in other languages like C, Java, Python and others. Hope you find this article helpful.
The above is the detailed content of Remove leading zeros from array using C++. For more information, please follow other related articles on the PHP Chinese website!