3

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?

3 Answers 3

9

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) { ... })

Sign up to request clarification or add additional context in comments.

Comments

0

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 .

Comments

0

.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; 
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.