Printing any array using FOR loop

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;
	}

}
closed account (zb0S216C)
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;
	}

}
So there isn't any alternative to explicitly defining the array size?
closed account (zb0S216C)
I'm afraid not. If somebody else finds away then I'll like to know myself.
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
closed account (zb0S216C)
Thats a good idea, propohetjohn. I'll use that myself.
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
Topic archived. No new replies allowed.