80

Is there a way of printing arrays in C++?

I'm trying to make a function that reverses a user-input array and then prints it out. I tried Googling this problem and it seemed like C++ can't print arrays. That can't be true can it?

  • 7
    It should be noted, if you're picky, that *C++* doesn't actually do any printing. All of that is taken care of by either the operating system directly of a library that sits on top of the OS, so naturally there are many ways to do it... such as the stdlib's cout, printf(), etc... – Faxwell Mingleton Sep 02 '09 at 21:55
  • 8
    The question itself is a bit flawed, tbh. Have you thought of what it even means to "print an array"? What is the data type on the array (number, string, user-defined, etc.)? How should the data be displayed? Do you need commas in the number? Do you want scientific notation? Should each element be on a separate line or do you want to distribute them in columns? Should columns be fixed width or dynamic? – Cogwheel Oct 28 '09 at 15:52

14 Answers14

73

Just iterate over the elements. Like this:

for (int i = numElements - 1; i >= 0; i--) 
    cout << array[i];

Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Botz3000
  • 39,020
  • 8
  • 103
  • 127
  • 1
    I'd also like to note, that in C++ world you mostly don't create a new, reversed array and then print it. Instead, you usually iterate the array in the other way: for (i = numElements-1; i>=0; i--) cout << array[i] << ","; – P Shved Sep 02 '09 at 21:55
  • You forgot to declare the i as an integer didn' you? That's what I did (well not really since I was supposed to reverse it).. so doing something like "for (int i = staerd-1; i >= 0; i--)" is the best way? –  Sep 02 '09 at 22:00
  • 14
    This version might overflow `int`, since the number of elements is `size_t`. Robust version is even more elegant: `for(size_t i = numElements; i--;)` – Maxim Egorushkin Apr 25 '16 at 09:08
  • 1
    @MaximEgorushkin I see your point, your solution seems to be the best way to do it. – Botz3000 Apr 27 '16 at 12:03
  • 3
    for(auto x: someArray){cout< – MartianMartian Oct 23 '18 at 16:27
  • @Martian2049 Not equivalent. – Lightness Races in Orbit Oct 23 '18 at 17:06
  • @LightnessRacesinOrbit Can you please elaborate on your comment? Why is MartianMartian's solution not equivalent? Do you recommend against this solution? Why? – MindSeeker Feb 14 '23 at 01:13
50

Use the STL

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ranges>

int main()
{
    std::vector<int>    userInput;


    // Read until end of input.
    // Hit control D  
    std::copy(std::istream_iterator<int>(std::cin),
              std::istream_iterator<int>(),
              std::back_inserter(userInput)
             );

    // ITs 2021 now move this up as probably the best way to do it.
    // Range based for is now "probably" the best alternative C++20
    // As we have all the range based extension being added to the language
    for(auto const& value: userInput)
    {
        std::cout << value << ",";
    }
    std::cout << "\n";

    // Print the array in reverse using the range based stuff
    for(auto const& value: userInput | std::views::reverse)
    {
        std::cout << value << ",";
    }
    std::cout << "\n";


    // Print in Normal order
    std::copy(userInput.begin(),
              userInput.end(),
              std::ostream_iterator<int>(std::cout,",")
             );
    std::cout << "\n";

    // Print in reverse order:
    std::copy(userInput.rbegin(),
              userInput.rend(),
              std::ostream_iterator<int>(std::cout,",")
             );
    std::cout << "\n";

}
Martin York
  • 257,169
  • 86
  • 333
  • 562
  • this I just ran this on gcc 4.6.1 using g++..it does not work –  Nov 02 '11 at 02:49
  • Just wondering whether there is any speed advantage with this approach? – Sam Stoelinga Dec 12 '13 at 07:13
  • @SamStoelinga: In speed terms. Always measure. I would use this for readability (thus maintainability). But iterators on vectors have always been considered very efficient so its not a worry I would really consider in most situations (unless speed was critical). – Martin York Dec 12 '13 at 08:50
37

May I suggest using the fish bone operator?

for (auto x = std::end(a); x != std::begin(a); )
{
    std::cout <<*--x<< ' ';
}

(Can you spot it?)

Pang
  • 9,564
  • 146
  • 81
  • 122
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
14

Besides the for-loop based solutions, you can also use an ostream_iterator<>. Here's an example that leverages the sample code in the (now retired) SGI STL reference:

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
  short foo[] = { 1, 3, 5, 7 };

  using namespace std;
  copy(foo,
       foo + sizeof(foo) / sizeof(foo[0]),
       ostream_iterator<short>(cout, "\n"));
}

This generates the following:

 ./a.out 
1
3
5
7

However, this may be overkill for your needs. A straight for-loop is probably all that you need, although litb's template sugar is quite nice, too.

Edit: Forgot the "printing in reverse" requirement. Here's one way to do it:

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
  short foo[] = { 1, 3, 5, 7 };

  using namespace std;

  reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
  reverse_iterator<short *> end(foo);

  copy(begin,
       end,
       ostream_iterator<short>(cout, "\n"));
}

and the output:

$ ./a.out 
7
5
3
1

Edit: C++14 update that simplifies the above code snippets using array iterator functions like std::begin() and std::rbegin():

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    short foo[] = { 1, 3, 5, 7 };

    // Generate array iterators using C++14 std::{r}begin()
    // and std::{r}end().

    // Forward
    std::copy(std::begin(foo),
              std::end(foo),
              std::ostream_iterator<short>(std::cout, "\n"));

    // Reverse
    std::copy(std::rbegin(foo),
              std::rend(foo),
              std::ostream_iterator<short>(std::cout, "\n"));
}
Void - Othman
  • 3,441
  • 18
  • 18
8

There are declared arrays and arrays that are not declared, but otherwise created, particularly using new:

int *p = new int[3];

That array with 3 elements is created dynamically (and that 3 could have been calculated at runtime, too), and a pointer to it which has the size erased from its type is assigned to p. You cannot get the size anymore to print that array. A function that only receives the pointer to it can thus not print that array.

Printing declared arrays is easy. You can use sizeof to get their size and pass that size along to the function including a pointer to that array's elements. But you can also create a template that accepts the array, and deduces its size from its declared type:

template<typename Type, int Size>
void print(Type const(& array)[Size]) {
  for(int i=0; i<Size; i++)
    std::cout << array[i] << std::endl;
}

The problem with this is that it won't accept pointers (obviously). The easiest solution, I think, is to use std::vector. It is a dynamic, resizable "array" (with the semantics you would expect from a real one), which has a size member function:

void print(std::vector<int> const &v) {
  std::vector<int>::size_type i;
  for(i = 0; i<v.size(); i++)
    std::cout << v[i] << std::endl;
}

You can, of course, also make this a template to accept vectors of other types.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
4

Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.

Printing arrays and dumping many different kinds of objects is a feature of higher level languages.

  • You can do it one statement in C++. I don't see this as a missing feature as using iterators makes it so much more powerful. Now I can abstract away where I am printing: it does not matter if the destination is console, pipe, file, another container, a function, a DB. It all looks and behaves the same. – Martin York Sep 02 '09 at 22:33
3

It certainly is! You'll have to loop through the array and print out each item individually.

Andy Mikula
  • 16,796
  • 4
  • 32
  • 39
  • 1
    standard algorithms dont require a loop. (though thay may use one internally). – Martin York Sep 02 '09 at 22:34
  • What if I don't have access to the STL? – Andy Mikula Sep 02 '09 at 22:46
  • Then you aren't using C++. Perhaps you're using Symbian/C++, or some subset of C++ provided by an embedded compiler. (Granted that technically, the STL is a precursor to the standard libraries in standard C++. But usually when people say "STL", they mean "the class and function templates in the C++ standard libraries", not the pre-standard STL. Hence STL is a subset of C++). – Steve Jessop Sep 03 '09 at 01:14
  • 4
    @Steve _"Then you aren't using C++"_ Not necessarily so. A freestanding implementation is explicitly permitted to omit all but a small collection of standard headers, and none of those mandated contains functionality inherited from the STL. [Further reading](http://eel.is/c++draft/compliance) – Lightness Races in Orbit Oct 23 '18 at 17:08
1

This might help //Printing The Array

for (int i = 0; i < n; i++)
{cout << numbers[i];}

n is the size of the array

1
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';

Works basically like foreach.

0

My simple answer is:

#include <iostream>
using namespace std;

int main()
{
    int data[]{ 1, 2, 7 };
    for (int i = sizeof(data) / sizeof(data[0])-1; i >= 0; i--) {
        cout << data[i];
    }

    return 0;
}
ej8000
  • 141
  • 1
  • 6
0

You can use reverse iterators to print an array in reverse:

#include <iostream>

int main() {
    int x[] = {1,2,3,4,5};
    for (auto it = std::rbegin(x); it != std::rend(x); ++it) 
        std::cout << *it;
}

output

54321

If you already reversed the array, you can replace std::rbegin and std::rend with std::begin/std::end, respectively, to iterate the array in forward direction.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

It's quite straightforward to copy the array's elements to a suitable output iterator. For example (using C++20 for the Ranges version):

#include <algorithm>
#include <array>
#include <iostream>
#include <iterator>

template<typename T, std::size_t N>
std::ostream& print_array(std::ostream& os, std::array<T,N> const& arr)
{
    std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
    return os;
}

Quick demo:

int main()
{
    std::array example{ "zero", "one", "two", "three", };
    print_array(std::cout, example) << '\n';
}

Of course it's more useful if we can output any kind of collection, not only arrays:

#include <algorithm>
#include <iterator>
#include <iosfwd>
#include <ranges>

template<std::ranges::input_range R>
std::ostream& print_array(std::ostream& os, R const& arr)
{
    using T = std::ranges::range_value_t<R>;
    std::ranges::copy(arr, std::ostream_iterator<T>(os, ", "));
    return os;
}

The question mentions reversing the array for printing. That's easily achieved by using a view adapter:

    print_array(std::cout, example | std::views::reverse) << '\n';
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
-2
// Just do this, use a vector with this code and you're good lol -Daniel

#include <Windows.h>
#include <iostream>
#include <vector>

using namespace std;


int main()
{

    std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
    
    if (arry.size() != arry.size() || arry.empty()) {
        printf("what happened to the array lol\n ");
        system("PAUSE");
    }
    for (int i = 0; i < arry.size(); i++)
    {   
        if (arry.max_size() == true) {
            cout << "Max size of array reached!";
        }
        cout << "Array Value " << i << " = " << arry.at(i) << endl;
            
    }
}
xo1337
  • 1
-4

If you want to make a function that prints every single element in an array;

#include <iostream>
using namespace std;

int myArray[] = {1,2,3,4, 77, 88};

void coutArr(int *arr, int size){
   for(int i=0; i<size/4; i++){
      cout << arr[i] << endl;
   }
}

int main(){
   coutArr(myArray, sizeof(myArray));
}

The function above prints every single element in an array only, not commas etc.

You may be wondering "Why sizeoff(arr) divided by 4?". It's because cpp prints 4 if there's only a single element in an array.

AikoDev
  • 1
  • 2