C Program to Reverse Array of Strings
Given an array of string literals, reverse the array.
Examples:
Input : arr[] = {"Coding", "Never", "Fail", "Me"}
Output : arr[] = {"Me", "Fail", "Never", "Coding"}
Input : arr[] = {"welcome", "to", "geeksforgeeks"}
Output : arr[] = {"geeksforgeeks", "to", "welcome"}
The idea is to create an array of pointers, store string literals in it. To reverse the array, we start from begin and end, and move both pointers toward each other. While moving, we keep swapping pointers.
// C program to reverse an array of strings #include <stdio.h> #include <string.h> void PrintArray(char* arr[], int n) { for (int i = 0; i < n; i++) { printf("%s ", arr[i]); } } void ReverseArray(char* arr[], int n) { char* temp; // Move from begin and end. Keep // swapping strings. int j = n - 1; for (int i = 0; i < j; i++) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j--; } } int main() { char* arr[] = { "Coding", "never", "fail", "me" }; int n = sizeof(arr) / sizeof(arr[0]); PrintArray(arr, n); printf("\n"); ReverseArray(arr, n); PrintArray(arr, n); return 0; } |
chevron_right
filter_none
Output:
Coding never fail me me fail never Coding
Recommended Posts:
- Program to copy the contents of one array into another in the reverse order
- Sort an array where a subarray of a sorted array is in reverse order
- First string from the given array whose reverse is also present in the same array
- C Program for Reverse a linked list
- Program to Reverse a String using Pointers
- Program to print Reverse Floyd's triangle
- Program to reverse a linked list using Stack
- Perl | Reverse an array
- C Program to reverse each node value in Singly Linked List
- Reverse an array upto a given position
- Sorting array with reverse around middle
- Reverse an array in groups of given size
- Reverse an array without using subtract sign ‘-‘ anywhere in the code
- Reverse an array without affecting special characters
- Reverse an array in groups of given size | Set 2 (Variations of Set 1 )
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



