C Program to Reverse an Array Using Array Itself as a Pointer
Question: write a program in C to reverse an array containing n elements using array name itself as a pointer.
C Source Code: Reversing Array Using Array Itself Pointer
When using array name itself as a pointer, note that array name always holds the address of first element in the array. In the following program, array name arr
is equivalent to &arr[0]
. So array name is considered as indirect pointer.
#include<stdio.h>
int main()
{
int arr[100],i,n, temp;
printf("How many numbers to read? (< 100): ");
scanf("%d", &n);
/* Reading array using array itself as a pointer */
printf("Enter %d numbers:\n", n);
for(i=0;i< n;i++)
{
printf("arr[%d] = ", i);
scanf("%d", (arr+i));
}
printf("\nOriginal array is: \n");
for(i=0;i< n;i++)
{
printf(" %d\t", *(arr+i));
}
/* Reversing array */
for(i=0;i< n/2;i++)
{
temp = *(arr + i);
*(arr + i) = *(arr + n -1 -i);
*(arr + n -1 -i) = temp;
}
/* Displaying reversed array content */
printf("\nReversed array is: \n");
for(i=0;i< n;i++)
{
printf(" %d\t", *(arr+i));
}
return 0;
}
Output
The output of the above program is:
How many numbers to read? (< 100): 5 Enter 5 numbers: arr[0] = 10 arr[1] = 20 arr[2] = 30 arr[3] = 40 arr[4] = 50 Original array is: 10 20 30 40 50 Reversed array is: 50 40 30 20 10