Cover Pic

Give an array or string and our problem is how to reverse this array(string)

Examples : 
 

Input  : arr[] = {9, 2, 3}
Output : arr[] = {3, 2, 9}

Input :  arr[] = {8, 5, 10, 3}
Output : arr[] = {3, 10, 5, 8}
Method 1 :- Recursive way
  • Define Start as 0 and end as n-1
  • swap the arr[start] and arr[end]
  • Recursively call the rest of the array.

Implementation of this method is given below

#include <stdio.h>

int main() {
	void reverseArr(int arr[],int start, int end)
	{
		if(start<end)
		{
			int temp;
			temp=arr[start];
			arr[start]=arr[end];
			arr[end]=temp;
			reverseArr(arr, start+1, end-1);
		}
		else return;
	}
	void printArr(int arr[],int size)
	{
		for(int i=0;i<size;i++)
		{
			printf("%d ",arr[i]);
		}
	}
	int arr[] = {8, 5, 10, 3};
    printArr(arr, 4);
    printf("\n");
    reverseArr(arr, 0, 3);
    printf("Reversed array is \n");
    printArr(arr, 4);   
    return 0;
}

Output : 

8 5 10 3 
Reversed array is 
3 10 5 8

Time Complexity : O(n)

Method 2: Iterative Method
  • Define start and end indexes as 0 and n-1 respectively
  • in a loop swap arr[start] and arr[end]. and increase start by 1 and decrease end by 1.
reverse-a-number

Below is the implementation of the program

int main() {
    void reverseArr(int arr[], int start, int end)
{
    while (start < end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
} 
    void printArr(int arr[],int size)
    {
        for(int i=0;i<size;i++)
        {
            printf("%d ",arr[i]);
        }
    }
    int arr[] = {8, 5, 10, 3};
    printArr(arr, 4);
    printf("\n");
    reverseArr(arr, 0, 3);
    printf("Reversed array is \n");
    printArr(arr, 4);   
    return 0;
}

Output : 

8 5 10 3 
Reversed array is 
3 10 5 8

Time Complexity : O(n)

For more Programming related blogs Visit Us Geekycodes . Follow us on Instagram.

If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com

Leave a Reply