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.
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() .
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.
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.
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]).
#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;
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With