Q:

C program to swap adjacent elements of a one dimensional array

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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;
    }
    //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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

One Dimensional Array Programs / Examples in C programming language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find occurrence of an element in one ... >>
<< C program to reverse array elements...