How to Reset int Array to Zero in C++?
Last Updated :
04 Mar, 2024
In C++, arrays store data of the same type in a contiguous memory location. To reset an int array means setting all elements to zero. In this article, we will see how to reset an integer array elements to zero in C++.
For Example,
Input:
int arr[] = { 10, 20, 30, 40, 50 };
Output:
Array after resetting: 0 0 0 0 0
Reset C++ int Array to Zero
In C++, there is no direct function to reset an array but it can be done by using the memset()
function from the cstring
library to set each element to zero.
Syntax of memset()
memset(arr, val, n);
Here,
- arr is a pointer to the array.
- val is the default value that is used to replace array elements (here 0).
- n is number of bytes to copy.
C++ Program to Reset an int Array to Zero
The below program demonstrates how we can reset an int array to zero in C++ using the memset
function.
C++
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 10, 20, 30, 40, 50 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << "Original array: " ;
for ( int i = 0; i < n; i++) {
cout << arr[i] << " " ;
}
cout << endl;
memset (arr, 0, n * sizeof (arr[0]));
cout << "Array after resetting: " ;
for ( int i = 0; i < n; i++) {
cout << arr[i] << " " ;
}
cout << endl;
return 0;
}
|
Output
Original array: 10 20 30 40 50
Array after resetting: 0 0 0 0 0
Time Complexity: O(N), where N is the size of the array.
Auxiliary Space: O(1)
Note: We can also use std::fill() function to reset an int array to zero in C++.
Share your thoughts in the comments
Please Login to comment...