Swap array's neighbouring elements using C Program

0
0

Create an array of 10 elements. And then swap the neighbouring elements.

If the array is

1 2 3 4 5 6 7 8 9 10

then after the operation, the array should be like this.

2 1 4 3 6 5 8 7 10 9
  • You must to post comments
0
0
#include <stdio.h>

int main()

{
int i , j=1;
int array[10], temp; // temp to hold the values while swaping

printf("Enter elements:\n");

for (i=0; i<10; i++){
    scanf("%d", &array[i]);
}

printf("\nThe initial array is:\n");

//Loop to print the array in initial order
for (i=0; i<10; i++){
    printf("%d ", array[i]);
}

/*Loop to swap the position*/
for (i=0; i<10; i+=2,j+=2){
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

printf("\nThe new array is:\n");

//Loop to print the array after swaping
for (i=0; i<10; i++){
    printf("%d ", array[i]);
}

   return 0;

}

 

  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.
Name*
E-mail*
Website