Question:

C programming: reversing the contents of an array?

by  |  earlier

0 LIKES UnLike

say I have a user input 5 integers and have them stored into an array.

say he chooses the integers [1,2,3,4,5], how can I then reverse the order of the contents of the array so that it becomes [5,4,3,2,1]?

*i dont need to know about the user input stuff, I have that, just would like to know how to reverse the contents of the array*

thanks.

 Tags:

   Report

2 ANSWERS


  1. There are several ways.  One would be to copy them to another array in reverse order.  (Last one in the array goes into the first of the new array, etc.)

    A second would be to exchange the first and the last in the array itself.  Because you can't simultaneously store both the old and the new values in the same place, you need a temporary variable to hold one value.

    You figure out the coding details.  Hope that helps.


  2. //assume that the array name is a

    int temp;

    int i ;

    for(i = 0;i<=(size/2);i++)

    {

    temp = a[i];

    a[i] = a[size-i];

    a[size-i] = temp;

    }

    This is just swapping elements  on either side of the middle of the array

    Hope this helps  

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.