An array is a data structure that stores similar data items at contiguous memory locations under one variable name. The elements in an array can be accessed using indices.
This article discusses the arrays and how to print array in C++.
Table of Contents
- Introduction of Arrays
- Different Methods to Print an Array in C++
- print array in C++ by Traversing Indices
- print array in C++ Using for_each() Function
- print array in C++ Using Range-Based for Loop
- print array in C++ Using Iterators
- print array Using ostream_iterator() Function and copy() Function
- print array Using C++17 copy() Function and make_ostream_joiner() Function
- Conclusion
Introduction of Arrays
For a small number of data items, you can use different variables for each data item, but when the number of instances grows, it becomes difficult to manage them with different variables.
In such conditions, arrays come in handy. The purpose of an array is to store many instances under a single variable name.
You can use arrays to store different data types such as int, float, double, char as well as complex data types such as class and structure objects. The array’s size and memory are both fixed.
Different Methods to Print an Array in C++
To print the arrays in C++, this article discusses the methods given below.
- By traversing indices
- Using
for_each()
function - Using range-based for loop
- Using Iterators
- Using
copy()
andostream_iterator()
library functions - Print array in C++17 using
copy()
andmake_ostream_joiner()
library functions
print array in C++ by Traversing Indices
You can access the array element using indices in the square brackets ([]).
To print the array,
- Start at index 0 and loop until the index is less than the length of the array.
- Print the element at the current index.
You can use any of the loops that C++ provides. The example given here uses the for
loop.
Syntax of the for
loop:
1 2 3 4 5 6 |
for (statement1; statement2; statement3) { // write the loop code here } |
Note that you can skip the first and the third statement if you have initialized the variable and updated it somewhere else. But you can not skip the second statement.
Let’s understand with code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> using namespace std; int main() { int n; // n is the size of above array; int array[] = {1,2,3,4,5,6}; n = sizeof(array)/sizeof (array[0]); for (int i=0; i<n; i++) { cout<<array[i]<<" "; } return 0; } |
Output:
Further reading:
print array in C++ Using for_each() Function
Apart from the generic looping technique that you have just seen, C++ has the for_each() function that you can use to print the array elements.
The for_each()
function lets you define a custom function and applies that function to all the array elements. It is found in the ‘algorithm’ header file.
Let us see the definition of the for_each()
function.
1 2 3 4 |
template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function fn); |
The function defines three parameters,
first
indicates the starting iterator of the array.last
indicates the iterator that marks the end of the arrays.fn
is the function that thefor_each()
function applies on each element of the array.
To print the array using the for_each()
function,
- Define a function that takes an integer argument and prints it.
- Pass the array iterators and the function to the
for_each()
function.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <algorithm> using namespace std; void printMyArr(int n) { cout<<n<<" "; } int main() { int n; // n is the size of above array; int array[] = {6, 5, 4, 3, 2, 1}; n = sizeof(array)/sizeof (array[0]); for_each(array, array+n, printMyArr); return 0; } |
Output:
print array in C++ Using Range-Based for Loop
C++11 introduced a new concept of the range-based for loop, that is far superior to the regular ‘for’ loop.
A range-based for loop does not necessitate extensive coding to implement loop iteration. It is a sequential iterator that iterates over each element of the container (from beginning to end).
Let us see the syntax of range-based for loop.
1 2 3 4 |
for (declaration: expression) loop statement |
- Declaration statement declares a variable with the same type as the elements of the array.
- Range expression defines an expression that represents the array.
- The loop statement is the body of the range-based for loop that contains statements that will be executed repeatedly until the end of the range expression.
Let’s understand with code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> using namespace std; int main() { double arr[] = {2.4, 4.5, 1.5, 3.5, 4.0, 6.7}; for (const auto &x : arr) { cout <<x<< " " ; } return 0; } |
Note that the code uses the auto
keyword to define the type of the variable in the loop. The auto
keyword instructs the compiler to automatically detect the data type of the array variables.
Output:
print array in C++ Using Iterators
Iterators are one of the four pillars of the C++ Standard Template Library, also known as the STL. An iterator points to the memory address of the STL container classes. To some extent, you can relate them with a pointer for better understanding.
Iterators serve as a link between algorithms and STL containers, allowing for changes to the data contained within the container. They enable you to iterate over the container, access and assign values and apply various operators to them.
To print the elements of the array, you must understand the following iterators.
begin()
: Thebegin()
function returns an iterator to the first element of the array.end()
: Theend()
function returns an iterator to the element following the container’s last element. Note that this does not point to the actual array element.
To print the array,
- Make use of any of the loops (including range-based for-loop).
- Start the loop for
begin()
iterator and traverse till theend()
iterator is reached. - Print the element at the current iterator using de-referencing operator (*).
Let’s understand with code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <array> #include <iostream> using namespace std; int main() { array<int, 6> arr{1, 2, 3, 4, 5, 6}; for (auto x = arr.begin(); x != arr.end(); ++x) cout << *x<<" "; return 0; } |
You can note a new way of declaring and initializing an array in C++. The code actually declares an array using the STL array class.
Output:
print array Using ostream_iterator() Function and copy() Function
C++ provides an output iterator ostream_iterator()
function that can write to an output stream. Therefore, you can use this function to print the array elements to the console (cout
stream).
The definition of the ostream_iterator() function is given below.
1 2 3 4 |
template <class T, class charT=char, class traits=char_traits<charT> > class ostream_iterator; |
You can pass the output stream and separator character to the function to print the array. The function is found in the iterator
header file.
However, to be able to print elements, you need another C++ function.
The copy() function lets you copy the elements within a range of iterators to an output iterator. The function is found in the algorithm
header file.
The definition of the copy()
method is given below.
1 2 3 4 |
template <class InputIterator, class OutputIterator> OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result); |
To print the array, you can call the copy()
function with the ostream_iterator()
function as the ‘result’ parameter.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <algorithm> #include <iterator> using namespace std; int main() { int n = 6; int array[6] = {1, 3, 5, 7, 9, 11}; copy(array, array+n, ostream_iterator<int>(cout, " ")); return 0; } |
Output:
print array Using C++17 copy() Function and make_ostream_joiner() Function
Similar to the ostream_iterator()
function shown in the previous section, make_ostream_joiner()
produces a legacy output iterator. The iterator can write the objects to the output stream.
The function was introduced in C++17. It is defined in the experimental/iterator
header file and the experimental
namespace.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <algorithm> #include <experimental/iterator> using namespace std; int main() { int n = 6; int array[6] = {1, 3, 5, 7, 9, 11}; copy(begin(array), end(array), experimental::make_ostream_joiner(cout, " ")); return 0; } |
Output:
Conclusion
The article discussed six different methods to print an array in C++. You can any of the methods according to your convenience.
However, you should note that in several places code uses arr
and arr+n
for iterators. This is perfectly valid as arr
is itself a pointer and holds the address of the first element.
Hope you have enjoyed reading the article. Stay tuned for more such articles.
Happy Learning!
References
- https://www.cplusplus.com/reference/algorithm/for_each/
- https://www.cplusplus.com/reference/algorithm/copy/?kw=copy
- https://www.cplusplus.com/reference/iterator/ostream_iterator/?kw=ostream_iterator
- https://en.cppreference.com/w/cpp/experimental/ostream_joiner/make_ostream_joiner