Write a c program for swapping of two arrays






Write a c program for swapping of two arrays


#include<stdio.h>
int main(){
  int a[10],b[10],c[10],i;
  printf("Enter First array->");
  for(i=0;i<10;i++)
  scanf("%d",&a[i]);
  printf("\nEnter Second array->");
  for(i=0;i<10;i++)
            scanf("%d",&b[i]);
  printf("Arrays before swapping");
  printf("\nFirst array->");
  for(i=0;i<10;i++){
            printf("%d",a[i]);
  }
  printf("\nSecond array->");
  for(i=0;i<10;i++){
            printf("%d",b[i]);
  }
  for(i=0;i<10;i++){
            //write any swapping technique
            c[i]=a[i];
            a[i]=b[i];
            b[i]=c[i];
  }
  printf("\nArrays after swapping");
  printf("\nFirst array->");
  for(i=0;i<10;i++){
            printf("%d",a[i]);
  }
  printf("\nSecond array->");
  for(i=0;i<10;i++){
            printf("%d",b[i]);
  }
  return 0;
}





6 comments:

  1. What to do if both arrays are of unequal length?

    ReplyDelete
    Replies
    1. just ur r swapping the elements of two arrays so, I think no need of equal length to swap each other

      Delete
    2. before dat in program they're reading 10 values for each array

      Delete
  2. Same program by using pointers.

    #include
    void swap(int *, int *);
    main()
    {
    int a[10],b[10],i;
    printf("Enter First array->");
    for(i=0;i<10;i++)
    scanf("%d",&a[i]);
    printf("\nEnter Second array->");
    for(i=0;i<10;i++)
    scanf("%d",&b[i]);
    for(i=0;i<10;i++)
    swap(&a[i], &b[i]);

    printf("\nArrays after swapping");
    printf("\nFirst array->");
    for(i=0;i<10;i++)
    printf("%d ",a[i]);

    printf("\nSecond array->");
    for(i=0;i<10;i++)
    printf("%d ",b[i]);
    }
    void swap(int *arr1, int *arr2)
    {
    int temp;
    temp = *arr1;
    *arr1 = *arr2;
    *arr2 = temp;
    }


    ReplyDelete
  3. can u write a program by using array......such as
    scanf 8 number then printf b[1]=1 b[2]=2 b[3]=3...b[8]=8 then convert it b[1]=8 b[2]=7....b[8]=1 ....please write this program...my fb id /mi.tanim.1

    ReplyDelete
  4. why dont you dynamically allocate array and change the address

    ReplyDelete