×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to reverse array elements

To reverse an array, swap the first and last elements, then the second and second-last, and so on until the middle is reached. This can be done using a loop or recursion.

Problem statement

Given an array, write a C program to reverse array elements.

Example

Input array elements are:
50, 10, 20, 40, 30

Output:
Sorted array elements are:
30, 40, 20, 10, 50

C program to reverse array elements

This C program will read N array elements and reverse them, this will print reversed array elements.

/*program to sort array elements in ascending order. */
#include <stdio.h>

/** funtion :   readArray() 
    input   :   arr ( array of integer ), size 
    to read ONE-D integer array from standard input device (keyboard). 
**/
void readArray(int arr[], int size)
{
    int i = 0;

    printf("\nEnter elements : \n");

    for (i = 0; i < size; i++) {
        printf("Enter arr[%d] : ", i);
        scanf("%d", &arr[i]);
    }
}

/** funtion :   printArray() 
    input   :   arr ( array of integer ), size 
    to display ONE-D integer array on standard output device (moniter). 
**/
void printArray(int arr[], int size)
{
    int i = 0;

    printf("\nElements are : ");

    for (i = 0; i < size; i++) {
        printf("\n\tarr[%d] : %d", i, arr[i]);
    }
    printf("\n");
}

void sortArray(int arr[], int size)
{
    int i = 0, j = 0, temp;

    for (i = 0; i < size - 1; i++) {
        for (j = i + 1; j < size; j++) {
            if (arr[i] > arr[j]) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

int main()
{
    int arr[5];

    readArray(arr, 5);

    printf("\nBefore Sorting");
    printArray(arr, 5);

    sortArray(arr, 5);

    printf("\nAfter Sorting");
    printArray(arr, 5);

    return 0;
}

Output

first run (when number of elements are EVEN)
Enter size of an Array :6 

Enter elements of Array 1: 
Enter 1 element :11 
Enter 2 element :22 
Enter 3 element :33 
Enter 4 element :44 
Enter 5 element :55 
Enter 6 element :66 
 
Array elements before reverse : 
   11   22   33   44   55   66 
Array elements After reverse : 
   66   55   44   33   22   11 

second run (when number of elements are ODD)
Enter size of an Array :5 

Enter elements of Array 1: 
Enter 1 element :11 
Enter 2 element :22 
Enter 3 element :33 
Enter 4 element :44 
Enter 5 element :55 

Array elements before reverse : 
   11   22   33   44   55 
Array elements After reverse : 
   55   44   33   22   11 

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.