A function to reverse an integer array source code

This snippet submitted by Major_Small on 2005-01-27. It has been viewed 71709 times.
Rating of 5.7 with 446 votes

    This function is used to reverse an integer array.  For example, if the
    array is {1,2,3,4,5}, these functions will return an array like {5,4,3,2,1}.
    The user needs to pass in a pointer to the array and the size of the array,
    and the function will return a pointer to an array in the reverse order.
    John Shao
    This work is hereby released into the Public Domain. To view a copy of the
    public domain dedication, visit

    or send a letter to

    Creative Commons
    559 Nathan Abbott Way
    Stanford, California 94305

int*ReverseArray(int*orig,unsigned short int b)
    unsigned short int a=0;
    int swap;
    for(a;a<--b;a++) //increment a and decrement b until they meet eachother
        swap=orig[a];       //put what's in a into swap space
        orig[a]=orig[b];    //put what's in b into a
        orig[b]=swap;       //put what's in the swap (a) into b
    return orig;    //return the new (reversed) string (a pointer to it)

/*                  The Following is a test program                           */
/* Note that this test program requires C++ but the function does not */

int main()
    const unsigned short int SIZE=10;
    int ARRAY[SIZE]={1,2,3,4,5,6,7,8,9,10};
    for(int i=0;i<SIZE;i++)
        std::cout<<arr[i]<<' ';
    for(int i=0;i<SIZE;i++)
        std::cout<<arr[i]<<' ';
    return 0;

More C and C++ source code snippets

Add a snippet!