zero fill in c++

#include <iostream>
#include <cstring>

int main() {
    const int size = 10;
    int array[size];

    std::memset(array, 0, sizeof(array));

    // Printing the zero-filled array
    std::cout << "Zero-filled array:" << std::endl;
    for (int i = 0; i < size; ++i) {
        std::cout << array[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

This C++ program demonstrates zero-filling an array using the memset function. Here's a step-by-step explanation:

  • #include <iostream>: Includes the input/output stream for handling input and output operations.
  • #include <cstring>: Includes the C string handling library for functions like memset.

  • const int size = 10;: Declares a constant variable size and initializes it to 10, representing the size of the array.

  • int array[size];: Declares an integer array named array with a size defined by the size constant.

  • std::memset(array, 0, sizeof(array));: Uses the memset function to set all elements in the array to zero. The memset function fills a block of memory with a particular value. Here, it sets 0 for each element in the array. The parameters are:

    • array: Pointer to the starting address of the memory block to be filled.
    • 0: The value (zero in this case) to be set.
    • sizeof(array): Specifies the number of bytes to be filled, which is calculated as the size of the array in bytes.
  • std::cout << "Zero-filled array:" << std::endl;: Outputs a message indicating the zero-filled array is being displayed.

  • for (int i = 0; i < size; ++i) { std::cout << array[i] << " "; }: Utilizes a for loop to iterate through each element of the array and prints its value followed by a space.

  • std::cout << std::endl;: Outputs a newline to move to the next line in the output.

  • return 0;: Indicates successful program execution and terminates the main() function.