C program to find reverse of an array

Write a C program to read elements in an array and find its reverse. C program to print reverse of an array. How to find reverse of an array elements.

Example:
If the elements of the array are: 10, 5, 16, 35, 500
Then its reverse would be: 500, 35, 16, 5, 10

That is if
array[0] = 10
array[1] = 5
array[2] = 16
array[3] = 35
array[4] = 500

Then after reversing array elements should be
array[0] = 500
array[1] = 35
array[2] = 16
array[3] = 5
array[4] = 10

Required knowledge:

Basic C programming, For Loop, Array

Algorithm:

Basic algorithm for reversing any array.
Step 1: Take two array say A and B. A will hold the original values and B will hold the reversed values.
Step 2: Read elements in array A.
Step 3: Set i=size - 1, j=0 (Where size is the size of array).
Step 4: Set B[j] = A[i]
Step 5: Set j = j + 1 and i = i - 1.
Step 6: Repeat Step 4-5 till i>=0.
Step 7: Print the reversed array in B.

Program:

/**
 * C program to find reverse of an array
 */

#include <stdio.h>

int main()
{
    int arr[100], reverse[100];
    int size, i, j;

    /*
     * Reads the size of array and elements in array
     */
    printf("Enter size of the array: ");
    scanf("%d", &size);
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    /*
     * Reverse the array
     */
    j=0;
    for(i=size-1; i>=0; i--)
    {
        reverse[j] = arr[i];
        j++;
    }

    /*
     * Prints the reversed array
     */
    printf("\nReversed array : ");
    for(i=0; i<size; i++)
    {
        printf("%d\t", reverse[i]);
    }

    return 0;
} 
Output
X
_
Enter size of the array: 5
Enter elements in array: 10 5 16 35 500

Reversed array : 500      35      16      5      10

Happy coding ;)


You may also like

Labels: , ,