Question

I would like to know if this is a suitable way to traverse through an array in c++.

     int array[] = {4,3,2};

     int n = 0;

    // traverse through array

    while (array[n] >=0){

    cout << array[n];
    n++;

   }

It works for me in my current problem to sort integer arrays.

Was it helpful?

Solution 2

This will only work if the data after your array is less than zero. In the typical case you cannot assume this, and so while this loop may work for now, eventually it will break. What you should be doing is looping from zero until you reach the length of the array instead:

for (int i = 0; i < 3; ++i)
    cout << array[i];

or, you can use the new range-for loop in C++11:

for (int i : array)
    cout << i;

Long story short: no. Your loop will not work 100% of the time, and therefore you should not use it.

OTHER TIPS

Why on earth do you thing that would work? Most of the time, it won't. If your array contains 0, it obviously won't, and if your array doesn't contain 0, it's very likely to continue too far (resulting in undefined behavior).

To traverse the array:

for ( int n: array ) {
    std::cout << n << std::endl;
}

Or in pre-C++11:

for ( int* current = begin( array ); current != end( array); ++ current ) {
    std::cout << *current << std::endl;
}

In C++11, you can also do this, and you don't even have to write your own versions of begin and end. Pre C++11, you'll need:

template <typename T, size_t n>
T* 
begin( T (&array)[n] )
{
    return array;
}

template <typename T, size_t n>
T*
end( T (&array)[n] )
{
    return array + n;
}

Put them in some universally included header.

Try this:

    int array[] = {4,3,2};

    // number of elements in array
    int const n = sizeof( array ) / sizeof( array[ 0 ] );

    // traverse through array and print each element
    for( int i = 0; i != n; ++i ) {
         cout << array[ i ];
    }

Here you are assuming that the index that doesn't have a value assigned by you will contain a -ve number, which isn't true.

You should always traverse using the size of the array:

for(i=0;i<size;i++) //here size is the size of the array
{
// operation on array
}
int array[] = {4,3,2};

for (size_t i = 0; i < 3; ++i)
{
    std::cout << array[i] << '\n';
}

Or in C++11

for (int x : array)
{
    std::cout << x << '\n';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top