eHow launches Android app: Get the best of eHow on the go.

How To

How to Reverse an Array

Contributor
By eHow Contributing Writer
(0 Ratings)

Virtually all programming languages use an array structure to store a list of data. For example, "array(76, 3, 5)." The reversed array would contain the same data but backwards i.e. "new_array(5, 3, 76)." Perl, a freely accessible programming language, allows you to implement a very elegant algorithm to reverse an array that requires only four lines of the code. The algorithm uses Perl built-in functions "pop" and "push."

Difficulty: Moderately Easy
Instructions

Things You'll Need:

  • Computer

    The Steps

  1. Step 1

    Obtain array data from the main program. Another array "new_array" will contain reversed data.

  2. Step 2

    Remove the last element from the initial array using the "pop" function.

  3. Step 3

    Add that element as the first one to the new array with "shift" function.

  4. Step 4

    Repeat Steps 2 and 3 until the initial array becomes empty; all its elements get transferred to the new one in reverse order.

  5. Step 5

    The working Perl program is below
    #Program starts
    my $array=[qw(1 2 6 7.4 25 9 12.6 2 6)]; #Example array
    my $new_array=[];
    print "@$array \n";
    reverse_array($array, $new_array);
    print "@$new_array \n"; #Printing the new array
    exit;

    sub reverse_array {
    my($array, $new_array)=@_; #Step 1. Read initial array
    while(@$array) {
    my $entry=pop (@$array); #Step 2. remove the last element of the initial array
    push @$new_array,$entry; #Step 3. Add that element to the new array as the first
    }
    }

  6. Step 6

    The program output is as follows
    1 2 6 7.4 25 9 12.6 2 6 <---initial array
    6 2 12.6 9 25 7.4 6 2 1 <---new array
    The array is reversed.

Resources
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Get Free Computers Newsletters

Copyright © 1999-2009 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US Portions of this page are modifications based on work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. † requires javascript

eHow Computers
eHow_eHow Technology and Electronics