Print Array in C++

Print Array in C++

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++.

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() and ostream_iterator() library functions
  • Print array in C++17 using copy() and make_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:

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

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.

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 the for_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.


6 5 4 3 2 1

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.

  • 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.

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.


2.4 4.5 1.5 3.5 4 6.7

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.

  1. begin(): The begin() function returns an iterator to the first element of the array.
  2. end(): The end() 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 the end() iterator is reached.
  • Print the element at the current iterator using de-referencing operator (*).

Let’s understand with code.

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.


1 2 3 4 5 6

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.

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.

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 3 5 7 9 11

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 3 5 7 9 11


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!



Was this post helpful?

Related Posts

  • 04 November

    Pass 2D Array to Function in C++

    Table of ContentsWays to Pass a 2D Array to function in C++Pass a 2D Array to a Function by Passing Its PointerPass an Array to the Function by Decaying the Pointer to the ArrayPass a 2D Array to a Function in C++ Without Size by Passing Its ReferenceConclusion Two-dimensional arrays have rows and columns, storing […]

  • 02 November

    Count Decimal Places in C++

    Table of ContentsAccuracy V/S Precision in Counting Decimal Places in C++ ProgramsHow to Count Decimal Places in C++Example 1: Use String Functions to Find Precise Number of Decimal PlacesExample 2: Count Decimal Places Accurately for a NumberExample 3: Create a Program that divides two numbers and returns their decimal placesExample 4: Find the Number of […]

  • 02 November

    Check if String Is Empty in C++

    Table of ContentsWays to Check if String Is Empty in C++Using Empty() methodUsing the Equality OperatorUsing length() methodUsing size() methodConclusion A String is a combination of characters that can store both alphabets and numbers together. In C, there was no concept of string as a datatype so character arrays were used. In C++, this drawback […]

  • 03 October

    Get Filename from Path in C++

    Table of ContentsGet Filename From Path in C++Using find_last_of and substr methodsUsing TemplatesUsing filesysystem library [ C++ 17 ]Conclusion This article explains the various ways to get filename from path using C++ programs. The examples will also describe ways to remove extensions as well if such needs arise. Get Filename From Path in C++ Finding […]

  • 24 September

    Escape Percent Sign in printf Method in C++

    In this post, we will see how to escape percent sign in printf Method in C++. Escape percent sign in Printf Method in C++ printf() method uses percent sign(%) as prefix of format specifier. For example: To use number in prinf() method, we use %d, but what if you actually want to use percent sign […]

  • 15 September

    Remove Last Element from Vector in C++

    Table of ContentsWays to Remove Last Element from Vector in C++Using the vector::pop_back() function to remove last element from vector in C++Using the vector::resize() Function to Remove Last Element from Vector in C++Using the vector::rrase() Function to Remove Last Element from Vector in C++Conclusion Learn about how to remove last element from Vector in C++. […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.