Open In App

How to Reset int Array to Zero in C++?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to illustrate how to reset an int array to
// zero
#include <cstring>
#include <iostream>
using namespace std;
  
int main()
{
    // Initialize an int array
    int arr[] = { 10, 20, 30, 40, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // print the original array
    cout << "Original array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
  
    // Reset the array by setting each element to 0 using
    // memset
    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++.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads