C Program To Display Elements of Array In Reverse Order using Pointers


Write a c program to display/print elements of an array in reverse order, using pointers.

Pointer Variable: Pointer variable is a variable which holds the address of another variable of same type.

Related Read:
C Program To Print Elements of Array In Reverse Order
Basics of Pointers In C Programming Language

Important Topic
Please watch this important video without fail: C Programming: Arrays, Pointers and Functions

Example: Expected Output

Enter 5 integer numbers
1
2
3
4
5

Elements of array in reverse order …
5
4
3
2
1

Visual Representation

print array elements in reverse order using pointers

Video Tutorial: C Program To Display Elements of Array In Reverse Order using Pointers


[youtube https://www.youtube.com/watch?v=CYf-rVrKNTI]

YouTube Link: https://www.youtube.com/watch?v=CYf-rVrKNTI [Watch the Video In Full Screen.]

Source Code: C Program To Display Elements of Array In Reverse Order using Pointers

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, *ptr;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    ptr = &a[N - 1];

    printf("\nElements of array in reverse order ...\n");
    for(i = 0; i < N; i++)
        printf("%d\n", *ptr--);

    return 0;
}

Output 1:
Enter 5 integer numbers
1
2
3
4
5

Elements of array in reverse order …
5
4
3
2
1
Output 2:
Enter 5 integer numbers
10
9
8
7
6

Elements of array in reverse order …
6
7
8
9
10

Logic To Display Elements of Array In Reverse Order using Pointers

We ask the user to input N integer numbers and store it inside array variable a[N]. We assign address of (N – 1)th element(last element of any array) to pointer variable ptr.

Inside for loop
We iterate through the for loop and for each iteration we print the value present at the address ptr. And for each iteration we decrement the value of ptr by 1.

This prints the array elements in reverse order.

Important Things To Note

1. Array elements are always stored in contiguous memory location.
2. A pointer when incremented always points to an immediately next location of its own type.

Explanation With Example

int a[5] = {5, 2, 6, 4, 3};
ptr = &a[4];

iptr*ptr–
010173
110134
210096
310052
410015

Output
3
4
6
2
5

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

Your email address will not be published. Required fields are marked *