Printing an array in C++ without a loop can be accomplished using a single command. This can be useful when dealing with larger arrays or when time complexity is a concern. In this tutorial, we will explore how to print an array in C++ without using a loop.
Steps:
1. Initialize the array with values.
1 |
int arr[] = {1, 2, 3, 4, 5}; |
2. Use std::vector to copy the array.
1 |
std::vector<int> vec(arr, arr + sizeof(arr) / sizeof(int)); |
3. Use the std::copy function to print the array.
1 |
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " ")); |
The above code will print the array without using a loop.
Conclusion:
Printing an array in C++ without a loop can be achieved by using the std::copy function from the standard library. This can make the program more efficient and reduce time complexity.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Example program #include <iostream> #include <algorithm> #include <iterator> #include <vector> int main() { int arr[] = {1, 2, 3, 4, 5}; std::vector<int> vec(arr, arr + sizeof(arr) / sizeof(int)); std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " ")); return 0; } |
Output:
1 2 3 4 5