Printing any array using FOR loop
Jan 24, 2011 at 1:06am UTC
I'm trying to print any array using this function but I need help dictating the end of any array. I thought I was on the right direction but it doesn't work.
1 2 3 4 5 6 7 8 9 10
template <typename xData>
xData Print(xData xArray[])
{
using namespace std;
for (int i = 0;xArray[i] != 0/; i++)
{
cout << xArray[i]<<endl;
}
}
Jan 24, 2011 at 1:07am UTC
As a parameter, get the user to set the size of the array like this:
1 2 3 4 5 6 7 8 9 10
template <typename xData>
xData Print(xData xArray[], unsigned uSize)
{
using namespace std;
for (int i = 0; i < uSize; i++)
{
cout << xArray[i]<<endl;
}
}
Jan 24, 2011 at 1:12am UTC
So there isn't any alternative to explicitly defining the array size?
Jan 24, 2011 at 1:13am UTC
I'm afraid not. If somebody else finds away then I'll like to know myself.
Jan 24, 2011 at 1:22am UTC
divide the size in bytes of the entire array by the size in bytes of the first element to get the number of elements in the array
1 2 3 4 5 6 7 8 9 10 11
template <typename xData>
xData Print(xData xArray[])
{
size = (sizeof (xArray) / sizeof (xArray[0]));
using namespace std;
for (int i = 0; i < size; i++)
{
cout << xArray[i]<<endl;
}
}
Last edited on Jan 24, 2011 at 1:25am UTC
Jan 24, 2011 at 1:28am UTC
Thats a good idea, propohetjohn. I'll use that myself.
Jan 24, 2011 at 1:38am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
using namespace std;
template <class T, unsigned N>
void Print(T (&xArray)[N])
{
for (unsigned i=0; i<N; i++)
cout << xArray[i] << ' ' ;
cout << endl;
}
int main()
{
int arr1[]={1,2,3,4,5};
double arr2[]={1.1,2.2,3.3};
char arr3[]={'a' ,'b' ,'c' ,'d' };
cout << "arr1: " ; Print(arr1);
cout << "arr2: " ; Print(arr2);
cout << "arr2: " ; Print(arr3);
cout << "\nhit enter to quit..." ;
cin.get();
return 0;
}
Last edited on Jan 24, 2011 at 1:38am UTC
Topic archived. No new replies allowed.