Rui Yu
Rui Yu

Reputation: 113

Reverse an array in c

I checked some videos of reversing an array in C therefore I know that my logic is correct. Here's my code:

#include <stdio.h>
void reverse( int arr[], unsigned int len )
{
int i=0;
int n=len;
int j=len-1;
int temp;

while (i<n) 
    {
        temp=arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
        i++;
        j--;
    }
}

void reverse( int arr[], unsigned int len ); 

int main( void )
{
  int a[] = {11, 19, 13};
  unsigned int len = 3;

  reverse( a, len );

  int k=0;
  for( k=0; k<len; k++ )
  {   
     printf( "%d ", a[k] );
  }
  printf( "\n" ); 

  return 0;
}

It outputs the same array. I couldn't find where the problem is. Should I return something for the reverse function?

Upvotes: 3

Views: 2300

Answers (3)

Dadhich Sourav
Dadhich Sourav

Reputation: 289

.Apart from this, for a good programming practice try to avoid the argument manually.for eg. in your code you have used, len,i,j,n by your side.

 #include <stdio.h>
void reverse( int arr[],int i,int j );
void reverse( int arr[], int i,int j )
{
int temp;
while (i<j) 
{
    temp=arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
    i++;
    j--;
  }
}
int main() 
{ 
 int arr[] = {11, 19, 13};
 int len=sizeof(arr)/sizeof(arr[0]);
  int i=0;
  int j=len-1;
  reverse( arr,i,j);
  for (int k=0; k <len; k++)
  printf("%d ", arr[k]);
  return 0; 
  }

Upvotes: 0

Suraj Jain
Suraj Jain

Reputation: 4536

You Are Reversing Your Array Twice , so once you reversed it , again you reverse it so it turning out to be same as original.

To Stop the reversing Do Not Run The Loop Till n , instead run it till j .

Upvotes: 0

Amadan
Amadan

Reputation: 198324

You are reversing the array twice; that's why you have the original array.

How? Take for an example a 10-element array. As your first step, you'll swap 0th and 9th element. As your last step, you'll swap 9th and 0th element. Net result: no change.

You don't want to run i up to n. You want to run i up to j, so that you never swap elements back (i.e. change the condition to while (i < j) { ... })

Upvotes: 9

Related Questions