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.

#include<stdio.h>

int main() {

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

   printf("Enter size of array:");
   scanf("%d", &num);

   printf("Enter 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("Array list after swapping:");
   for (i = 0; i < num; i++) {
       printf("%d ", arr[i]);
   }

   return 0;
}

Output:

Enter size of array:6                                                                                                                  
Enter array elements:10 20 30 40 50 60                                                                                                 
Array list after swapping:20 10 40 30 60 50