Reverse the array elements using pointers

C program to print the array elements in reverse order using pointers.

Program

#include<stdio.h>
#include<conio.h>
#define MAX 50;
void main()
{
	int arr[MAX];
    int n, i;
    int *ptr;

    printf("Enter the size of the array\t:");
    scanf("%d",&n);

    printf("\nEnter elements in the array\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }

    ptr = arr+n-1;   //ptr points to the last element in the array
                     //ptr = &arr[n-1]

    printf("\nElements in the array in reverse order are\n");
    for(i=0;i<n;i++)
    {
        printf("%d\n",*ptr);
        ptr--;
    }

    getch();
}

Output

Enter the size of the array     :5

Enter elements in the array
1
3
5
7
9

Elements in the array in reverse order are
9
7
5
3
1

Explanation

In the above program, an integer array 'arr' is declared and a pointer variable 'ptr' is declared.
ptr = arr;, 'ptr' points to 'arr[0]' element of the array.

We have to print the array in reverse order.
So, for this purpose, we will have to point pointer 'ptr' to the last element of the array. This is done using the following statement:
ptr = arr+n-1
or
ptr = &arr[n-1]
Now, 'ptr' points to the last element of the array.

Now, we have to print the array, for this *ptr is used.
for(i=0;i<n;i++)
{
printf("%d\n",*ptr);
ptr--;
}
Initially 'ptr' points to 'arr[n-1]'. So, *ptr will give the value stored in arr[n-1].
This value is printed and pointer is decremented (ptr--) to point to the previous element of the array.
The above process is repeated 'n' number of times.