C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs



Home » C programs » C One Dimensional Array programs

C program to swap first element with last, second to second last and so on (reversing elements)






In this C program, we are going to swap array elements (like, first element with last, second element with second last and so on... i.e. reversing the array elements).
Submitted by IncludeHelp, on April 14, 2018

Given an array of integer elements and we have to reverse elements (like, swapping of first element with last, second element with second last and so on) using C program.

Example:

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

    Output:
    Array elements after swapping (reversing):
    50, 40, 30, 20, 10

Program to reverse array elements (by swapping first element to last, second to second last and so on) in C

/** C program to swap first element with last,
 * second element with second last and so on in
 * an array.
*/

#include <stdio.h>

// function to swap the array elements
void Array_Swap(int *array , int n)
{ 
    // declare some local variables
    int i=0,temp=0;

    for(i=0 ; i<n/2 ; i++)
    {
        temp = array[i];
        array[i] = array[n-i-1];
        array[n-i-1] = temp;
    }
}

// main function
int main()
{
    // declare an int array
    int array_1[30] = {0};
    
    // declare some local variables
    int i=0 ,n=0;
    
    printf("\nEnter the number of elements for the array : ");
    scanf("%d",&n);
   
    printf("\nEnter the elements for array_1..\n");
    for(i=0 ; i<n ; i++)
    {
        printf("array_1[%d] : ",i);
        scanf("%d",&array_1[i]);
    }
    
    // Sort the array in ascending ordder
    Array_Swap(array_1 , n);

    printf("\nThe array after swap is..\n");
    for(i=0 ; i<n ; i++)
    {
        printf("\narray_1[%d] : %d",i,array_1[i]);
    }
    
    return 0;
}



Output

Run 1:

Enter the number of elements for the array : 6  
 
Enter the elements for array_1.. 
array_1[0] : 1   
array_1[1] : 2   
array_1[2] : 3   
array_1[3] : 4   
array_1[4] : 5   
array_1[5] : 6   
 
The array after swap is..
 
array_1[0] : 6   
array_1[1] : 5   
array_1[2] : 4   
array_1[3] : 3   
array_1[4] : 2   
array_1[5] : 1






You may also be interested in...

C/C++ Tips and Tricks...

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.


Comments and Discussions