Remove Leading Zeros from an Array using C++

C++Server Side ProgrammingProgramming

We are provided an array, and we are tasked to remove the 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 make a new array that doesn’t contain the leading zeroes of the previous array in the given problem.

Approach to find The Solution

In this approach, we will go through the array and insert all the numbers but no leading zeros.

Example

#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] << " ";
   }
}

Output

1 2 0 4

Explanation of the above code

In the given program, we are firstly traversing through the array arr and finding the first non-zero element's index, which we store in variable called last now if last is -1 after the traversal, so that means our whole array is made up of zeroes, so we print our "Empty."

Now, as we got the index of the first non-zero elements, we can determine our new array's size, i.e. (n - last), and now we run a for loop from last till less than n. We insert these elements in the new array and print the new array.

Conclusion

In this article, we solve a problem to Remove leading zeros from an array. We also learned the C++ program for this problem and the complete approach we solved. We can write the same program in other languages such as C, java, python, and other languages. We hope you find this article helpful.

raja
Updated on 29-Nov-2021 09:42:10

Advertisements