In this tutorial, we will learn how to remove null values from an Array in C++. It is important to remove the null value for Memory Optimization,Efficient Data Processing, and Data Integrity purposes. Removing null values from arrays is a common task in C++ programming, especially in data processing and algorithm development
Approaches to remove null value from an array
- First, we create a new array where we store the values without null values.
- Then we copy values from the original array to our new array.
- When we found a null value then we skipped the value and shifted the non-null values.
Remove null values from an array in C++
#include <iostream> using namespace std; void removeNulls(int arr[], int& size) { int j = 0; for (int i = 0; i < size; ++i) { if (arr[i] != 0) { arr[j++] = arr[i]; } } size = j; } int main() { int array[] = {1, 2, 0, 4, 0, 6, 0, 8}; int size = sizeof(array) / sizeof(array[0]); cout << "Original array: "; for (int i = 0; i < size; ++i) { cout << array[i] << " "; } cout << endl; removeNulls(array, size); cout << "Array after removing nulls: "; for (int i = 0; i < size; ++i) { cout << array[i] << " "; } cout << endl; return 0; }
Output:-
Original array: 1 2 0 4 0 6 0 8 Array after removing nulls: 1 2 4 6 8
Here we use “0” as a null value.
In this Code, you can see we are giving input [1,2,0,4,0,6,0,8], and we get output a [1,2,4,6,8] we easily remove the null values from the original array, here we use “0” as a null value.