Home > Backend Development > C++ > body text

Remove leading zeros from array using C++

PHPz
Release: 2023-09-05 11:13:11
forward
883 people have browsed it

Remove leading zeros from array using C++

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
Copy after login

We can create a new array that does not contain the leading zeros of the previous array in the given problem.

Method to find the solution

In this method we will iterate through the array and insert all numbers except 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] << " ";
   }
}
Copy after login

Output

1 2 0 4
Copy after login

Explanation of the above code

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.

Conclusion

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!