Reverse Array Elements in C

0

Arrays are a fundamental concept in programming. They allow us to store multiple values in a single variable and perform operations on them efficiently. One of the most common operations performed on arrays is to reverse their order. In this blog post, we will discuss how to reverse an array in C programming using a simple program example.

What is Reversing an Array?

Reversing an array means changing the order of its elements, so that the first element becomes the last, the second becomes the second-to-last, and so on. Reversing an array can be useful in a variety of programming scenarios, such as when we need to iterate through an array in reverse order or when we want to display the array elements in a different order. The program example we will be discussing in this blog post will demonstrate how to reverse an array in C programming.

#include<stdio.h>
#include<math.h>

int main(void)
{

    int n = 0;

    printf("Enter the length of an array: ");
    scanf("%d", &n);

    int elem[n];

    for(int i=0; i<n; i++)
    {
        printf("Enter the number %d: ", i+1);
        scanf("%d", &elem[i]);
    }

    printf("\n");

    for(int i = n-1; i >= 0; i--)
    {
        printf("Element %d is: %d\n", n-i, elem[i]);
    }

    return 0;
}

The code for this program is quite simple and can be broken down into a few parts. The program consists of three main parts. Firstly, we define the variables needed, which includes the length of the array and the elements of the array.

Next, we ask the user to enter the length of the array. Using this value, we allocate the required memory and use a for-loop to input the elements of the array.

Finally, we use another for-loop to print the elements of the array in reverse order. Starting at the end of the array, we move towards the beginning and print each element.

Output

Enter the length of an array: 4
Enter the number 1: 7
Enter the number 2: 2
Enter the number 3: 9
Enter the number 4: 1

Element 1 is: 1
Element 2 is: 9
Element 3 is: 2
Element 4 is: 7

In conclusion, printing an array in reverse order is a straightforward process in C programming language. With the use of for-loops and basic knowledge of arrays, this task can be accomplished with ease. This program is a great example of how C programming language can be used to manipulate data structures such as arrays.

LEAVE A REPLY

Please enter your comment!
Please enter your name here