How to fill all elements of an array with 0 in C++

3 Answers

0 votes
#include <iostream>
#include <array>

template <typename T>
void print(const T &arr) {
    for (const auto &element : arr) {
        std::cout << element << ' ';
    }
    std::cout << "\n";
}
 
int main()
{
    std::array<int, 5> arr;
 
    arr.fill(0);
 
    print(arr);
}
 
 
 
/*
run:
 
0 0 0 0 0 
 
*/

 



answered Dec 12, 2024 by avibootz
0 votes
#include <iostream>
#include <cstring> 

template <typename T>
void print(const T &arr) {
    for (const auto &element : arr) {
        std::cout << element << ' ';
    }
    std::cout << "\n";
}


int main() {
    int arr[5];
    
    memset(arr, 0, sizeof(arr));
    
    print(arr);
}
 
 
 
/*
run:
 
0 0 0 0 0 
 
*/

 



answered Dec 12, 2024 by avibootz
0 votes
#include <iostream>

template <typename T>
void print(const T &arr) {
    for (const auto &element : arr) {
        std::cout << element << ' ';
    }
    std::cout << "\n";
}


int main() {
    int arr[5] = {0};

    print(arr);
}
 
 
 
/*
run:
 
0 0 0 0 0 
 
*/

 



answered Dec 12, 2024 by avibootz

Related questions

1 answer 82 views
1 answer 207 views
1 answer 101 views
1 answer 69 views
1 answer 105 views
1 answer 102 views
1 answer 98 views
...