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

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




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Empty an Array in C++? How to Empty an Array in C++?
How to Find the Maximum Key in a Map in C++? How to Find the Maximum Key in a Map in C++?
How to Find Intersection of Two Sets in C++? How to Find Intersection of Two Sets in C++?
How to Remove a Key-Value Pair from Map in C++? How to Remove a Key-Value Pair from Map in C++?
How to Pop an Element From a Stack in C++? How to Pop an Element From a Stack in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14