# C program to swap adjacent elements of a one dimensional array

Given N array elements and we have to swap adjacent elements using C program.

In this C program, we are going to learn how to swap adjacent elements of a given array of N 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
```

Program:

```/*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;
}
printf("Enter array elements:\n");
for(i=0;i < n;i++)
{
printf("Enter element %d:",i+1);
scanf("%d",&arr[i]);
}
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
```

Top MCQs

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates