CS Electrical And Electronics
@cselectricalandelectronics

How do you reverse an array?

All QuestionsCategory: Data StructureHow do you reverse an array?
chetan shidling asked 4 years ago

I need short information.

1 Answers
chetan shidling answered 4 years ago

For example:
1 2 3 4 is input.
The output should be 4 3 2 1
 
First, interchange starting and end number, then increment the starting and decrement the end. For example:
 
void rvereseArray(int arr[], int start, int end)
{
    int temp;
    while (start < end)
    {
        temp = arr[start];   
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }   
}     
  
 
void printArray(int arr[], int size)
{
  int i;
  for (i=0; i < size; i++)
    printf("%d ", arr[i]);
  
  printf("\n");
} 
 
 
int main() 
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof(arr) / sizeof(arr[0]); 
    printArray(arr, n);
    rvereseArray(arr, 0, n-1);
    printf("Reversed array is \n");
    printArray(arr, n);    
    return 0;
}
 
 
The output will be 6 5 4 3 2 1