EnglishFrenchGermanSpainItalianDutchPortugueseRussianKoreanJapaneseArabic Chinese Simplified

Sunday, April 24, 2011

Function to reverse an integer array

This function(ReverseArray 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. 

 // this code was copied from cprogramming.com
// my respects for posting this code with
// no official whereabouts as to where it was from


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
#include<iostream>

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

 

Artikel Terkait:

Comments :

0 comments to “Function to reverse an integer array”

Post a Comment

 

Copyright © 2009 by Learn Technology

Template by Blogger Templates | Powered by Blogger