C Program to swap adjacent elements of an array


In this program, You will learn how to swap adjacent elements of an array in c.


List is: 1, 2, 3, 4, 5, 6

After swap: 2, 1, 4, 3, 6, 5


Example: How to swap adjacent elements of an array in c

Run it Now
#include<stdio.h>

int main() {

   int i, t, num, arr[100];

   printf("Enter Size of Array :");
   scanf("%d", &num);

   printf("\nEnter Array Elements :");
   for (i = 0; i < num; i++) {
       scanf("%d", &arr[i]);
   }

   i = 0;
   while (i < num - 1) {
       t = arr[i];
       arr[i] = arr[i + 1];
       arr[i + 1] = t;
       i = i + 2;
   }

   printf("\nArray List After Swapping :");
   for (i = 0; i < num; i++) {
       printf("%d ", arr[i]);
   }

   return 0;
}

Output:

Enter Size of Array :6
Enter Array Elements :1 2 3 4 5 6
Array List After Swapping :2 1 4 3 6 5