C Program to Print Array Elements in Reverse Order

In this article, we will write a C program to print array elements in reverse order. The program walks through the array in the reverse order and prints each element on the output screen.

Sample Example:

Original Array: 1 2 3 4 5
Array in Reverse Order: 5 4 3 2 1

In C programming, an array is a collection of similar data types that are stored in contiguous memory locations.

Because the items of the array are stored in contiguous memory locations, therefore, we can access them using their index in the array.

You have to note that the array index starts at 0 instead of 1. What it means is that the index of the first item of the array will always be 0, index of the second item will be 1 and so on.

As we want to print the array items in the reverse order, we need to know the last index of the array, which is always array length – 1.

last index of array = length of array - 1

So, to print the array in the reverse order, we will basically start from the last index of the array and move towards the beginning of the array in step of -1.

See implementation in the following C program:

// C Program to print the array elements in reverse order

#include <stdio.h>

int main() {
	
	// Initialize the array
	int arr[] = {1, 2, 3, 4, 5};
	
	// Calculate the length of the array
	int length = sizeof(arr)/sizeof(arr[0]);
	
	printf("Original Array: ");
	for(int i = 0; i < length; i++){
		printf("%d ", arr[i]);
	}
	
	printf("\nArray in Reverse Order: ");
	for(int i = length - 1; i >= 0; i--){
		printf("%d ", arr[i]);
	}
	
	return 0;

}

Output:

Original Array: 1 2 3 4 5
Array in Reverse Order: 5 4 3 2 1

Program Explanation:

The program starts by declaring an array of int data type. After declaring the array, we calculated the length of the array using the sizeof() function.

When we pass an array as an argument to the sizeof() function, it returns the total space reversed by the array in the memory in bytes. Therefore, to calculate the length of the array, we can divide the total size of the array by the size taken by the first element of it.

Once the length of the array is calculated, we used a for loop to print the array elements in reverse order.

I hope you will find this article helpful. Thanks for reading!

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts

Leave a Comment