Q:

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

0

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

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find nearest lesser and greater eleme... >>
<< C program to count Array elements by using sizeof(...