Home » C programs » C One-D Array programs

C program to swap adjacent elements of a one dimensional array



This C program will read N array elements and swap adjacent elements.

Example

    Enter total number of elements: 10
    Enter array elements:
    Enter element 1: 10
    Enter element 2: 20
    Enter element 3: 30
    Enter element 4: 40
    Enter element 5: 50
    Enter element 6: 60
    Enter element 7: 70
    Enter element 8: 80
    Enter element 9: 90
    Enter element 10: 100

    Array elements after swapping adjacent elements:
    20
    10
    40
    30
    60
    50
    80
    70
    100
    90
/*C program to swap adjacent elements of an one dimensional array.*/

#include <stdio.h>
#define MAX 100
int main()
{
	int arr[MAX],n,i;
	int temp;
	
	printf("Enter total number of elements: ");
	scanf("%d",&n);
	
	//value of n must be even
	if(n%2 !=0)
	{
		printf("Total number of elements should be EVEN.");
		return 1;
	}
	//read array elements
	printf("Enter array elements:\n");
	for(i=0;i < n;i++)
	{
		printf("Enter element %d:",i+1);
		scanf("%d",&arr[i]);
	}
	//swap adjacent elements
	for(i=0;i < n;i+=2)
	{
		temp	= arr[i];
		arr[i]	= arr[i+1];
		arr[i+1]= temp;
	}
	
	printf("\nArray elements after swapping adjacent elements:\n");
	for(i=0;i < n;i++)
	{
		printf("%d\n",arr[i]);
	}
	return;
}
    

Output

    First Run:
    Enter total number of elements: 11
    Total number of elements should be EVEN.

    Second Run:
    Enter total number of elements: 10
    Enter array elements:
    Enter element 1: 10
    Enter element 2: 20
    Enter element 3: 30
    Enter element 4: 40
    Enter element 5: 50
    Enter element 6: 60
    Enter element 7: 70
    Enter element 8: 80
    Enter element 9: 90
    Enter element 10: 100

    Array elements after swapping adjacent elements:
    20
    10
    40
    30
    60
    50
    80
    70
    100
    90





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.