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++.
[toc]
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:
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.
#includeusing 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 Output:
1 2 3 4 5 6Further 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.templateFunction for_each (InputIterator first, InputIterator last, Function fn); The function defines three parameters,
firstindicates the starting iterator of the array.lastindicates the iterator that marks the end of the arrays.fnis 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.
#include#include using namespace std; void printMyArr(int n) { cout< Output:
6 5 4 3 2 1print 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.
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.
#includeusing namespace std; int main() { double arr[] = {2.4, 4.5, 1.5, 3.5, 4.0, 6.7}; for (const auto &x : arr) { cout < Note that the code uses the
autokeyword to define the type of the variable in the loop. Theautokeyword instructs the compiler to automatically detect the data type of the array variables.Output:
2.4 4.5 1.5 3.5 4 6.7print 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.
#include#include using namespace std; int main() { array 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:
1 2 3 4 5 6print 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 (coutstream).The definition of the ostream_iterator() function is given below.
template> 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
iteratorheader 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
algorithmheader file.The definition of the
copy()method is given below.templateOutputIterator copy (InputIterator first, InputIterator last, OutputIterator result); To print the array, you can call the
copy()function with theostream_iterator()function as the 'result' parameter.Let us see the code.
#include#include #include using namespace std; int main() { int n = 6; int array[6] = {1, 3, 5, 7, 9, 11}; copy(array, array+n, ostream_iterator (cout, " ")); return 0; } Output:
1 3 5 7 9 11print 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/iteratorheader file and theexperimentalnamespace.Let us see the code.
#include#include #include 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:
1 3 5 7 9 11Conclusion
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
arrandarr+nfor iterators. This is perfectly valid asarris 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