Reverse of an Array in C
Reverse of an array in C Programming Language
On this page, we will look into a coding question where we will learn how to reverse the array in C Programming Language. There might be different approaches to solve this question, one you will find here. If your approach is a bit different post it in the comment section.
Reverse of an Array In C
In C programming language, an array is a collection of elements of the same type stored in contiguous memory locations. To reverse an array in C, you need to swap the elements of the array in a specific order.
One way to reverse an array is to use two pointers, one pointing to the first element of the array and the other pointing to the last element of the array. Then, swap the elements at the two pointers and move the pointers towards each other until they meet at the middle of the array.
Algorithm:
- Initialize two pointers
start_ptr
andend_ptr
to the first and last elements of the array, respectively. - While
start_ptr
is less thanend_ptr
, do the following:- Swap the elements pointed to by
start_ptr
andend_ptr
. - Increment
start_ptr
by 1. - Decrement
end_ptr
by 1.
- Swap the elements pointed to by
- When the loop terminates, the array will be reversed.
Program for reversing an array in C
#include<stdio.h> int main() { int n; scanf("%d",&n); int arr[n]; int temp; for(int i=0; i<n; i++) { scanf("%d",&arr[i]); } for(int i=0; i<n/2; i++) { temp = arr[i]; arr[i] = arr[n-i-1]; arr[n-1-i] = temp; } for(int i=0; i<n; i++) { printf("%d ",arr[i]); } return 0; }
Output:
5
2 5 1 4 3
3 4 1 5 2
Login/Signup to comment