Question:
How do I reverse an array?
friedsquirrel17
2013-11-22 17:42:24 UTC
Write the definition of a function reverse , whose first parameter  is an array  of integers  and whose second parameter  is the number of elements  in the array . The function reverses the elements  of the array . The function does not return a value .

I believe the beginning would look like this:

void reverse(int array[ ], int size)
{
int i;
for(i=0; i//Not sure what to do now
}
Six answers:
husoski
2013-11-22 18:19:35 UTC
If the goal is to reverse that array in-place, then you really want to stop at size/2 instead of size in that for loop.



Inside the loop, using a int temporary variable, swap the contents of array[i] with array[size-1-i]:



int temp = array[i];

array[i] = array[size-1-i]

array[size-1-i] = temp;



If you run that with i ranging from 0 to size-1, then you will reverse the array twice, leaving it in the original order. Not good.



for (i=0; i
for (i=size/2 - 1; i>=0; --i) .... this works too



The second version avoids computing and storing size/2 for comparison. Older, unoptimized compilers would compute size/2 on every iteration of the loop.



Also, you might occasionally see (size>>1) instead of size/2. Shifts are faster than division, and C/C++ compilers can't optimize signed integer division by 2 into shifts because of the bonehead rounding modes that ISO/ANSI chose.



For now, just use the first version, and be aware that the others exist. You probably won't have to worry about this sort of micro-optimization, ever.
?
2017-01-21 21:35:50 UTC
1
Ram Theleader
2013-11-22 17:51:02 UTC
If you are size is ''N'' ,then you have to start the ''for'' loop from the ''N'' to the ''0''...then print the array..now it in the reverse order...

The code looks like this ::



for(i=n;i>0;i++)

{

printf('' %d '',array[i]),

}



Thank you.array of integers with three elements such that

a[0] = 1

a[1] = 2

a[2] = 3

Then on reversing the array will be

a[0] = 3

a[1] = 2

a[0] = 1
Clark Alan
2013-11-22 20:44:57 UTC
Refer this

http://www.programmingsimplified.com/c-program-reverse-array
Puter_Notgeek
2013-11-22 17:43:56 UTC
Why not start from the end?

int i;

for(i=size-1; i >=0; i--)

Wait..did you mean in same array?



int temp;

for(int i = 0; i < array.length/2; i++)

{

temp = array[i];

array[i] = array[array.length - i - 1];

array[array.length - i - 1] = temp;

}



for (int i = 0; i < array.length; i++)

System.out.println("array " +a[i]);
nicefx
2013-11-22 17:45:21 UTC
just change expression in for()



for (i=size-1; i>=0; i--)

..

..

..


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Continue reading on narkive:
Loading...