Program to reverse an array or string

Program to reverse an array or string
Given an array (or string), the task is to reverse the array/string.
Method 1(Iterative way):
// Iterative C program to reverse an array
#include<stdio.h>
/* Function to reverse arr[] from start to end*/
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--;
    }  
}    
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
  int i;
  for (i=0; i < size; i++)
    printf("%d ", arr[i]);
  printf("\n");
}
/* Driver function to test above functions */
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    printArray(arr, 6);
    rvereseArray(arr, 0, 5);
    printf("Reversed array is \n");
    printArray(arr, 6);   
    return 0;
}
Output :
1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1
Method 2(recursive way):
// Recursive C program to reverse an array
#include <stdio.h>
/* Function to reverse arr[] from start to end*/
void rvereseArray(int arr[], int start, int end)
{
   int temp;
   if (start >= end)
     return;
   temp = arr[start];  
   arr[start] = arr[end];
   arr[end] = temp;
   rvereseArray(arr, start+1, end-1);  
}    
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
  int i;
  for (i=0; i < size; i++)
    printf("%d ", arr[i]);
  printf("\n");
}  
/* Driver function to test above functions */
int main()
{
    int arr[] = {1, 2, 3, 4, 5, 6};
    printArray(arr, 6);
    rvereseArray(arr, 0, 5);
    printf("Reversed array is \n");
    printArray(arr, 6);   
    return 0;
}
Output :
1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1
Examples :
Input  : arr[] = {1, 2, 3}
Output : arr[] = {3, 2, 1}
Input :  arr[] = {4, 5, 1, 2}
Output : arr[] = {2, 1, 5, 4}

Program to reverse an array or string Program to reverse an array or string Reviewed by Unknown on August 24, 2018 Rating: 5

No comments:

If you have any doubt or query ,comment below:

Programming copyright © 2018-19. Powered by Blogger.