Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cout a whole array in c++

I am fairly new to c++, is there a way in c++ through which we can cout a whole static array apart from iterating via a for loop?

int arra[10] = {1,2,3,4};
std::cout << arra << std::endl;

I tried this but, this is printing address of the first element in the array.

like image 944
rahul Avatar asked Oct 30 '15 15:10

rahul


People also ask

How do you cout an entire array?

std::copy(arra, arra + 10, std::ostream_iterator<int>(cout, "\n")); If you want to write good code, you could use std::array and then simply write arra. begin() and arra. end() .

Can you print whole array in C?

This program will let you understand that how to print an array in C. We need to declare & define one array and then loop upto the length of array. At each iteration we shall print one index value of array. We can take this index value from the iteration itself.

How do you print an array?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.

Can we print array in C without loop?

Ya, we can. If the array size is fixed, for example if the array's size is 6. Then you can print the values like printf(a[0]) to printf(a[5]).


2 Answers

#include<iostream>        
using namespace std;

int main(){ int i;

int myarr[5]={9,84,7,55,6};
for(i=0;i<5;i++){

    cout<<myarr[i]<<endl;
}

}

like image 99
Revealer Avatar answered Oct 24 '22 08:10

Revealer


Following doesn't use (explicitly) loop:

std::copy(std::begin(arra),
          std::end(arra),
          std::ostream_iterator<int>(std::cout, "\n"));

but loop seems simpler to read/write/understand:

for (const auto& e : arra) {
    std::cout << e << std::endl;
}
like image 36
Jarod42 Avatar answered Oct 24 '22 08:10

Jarod42