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





12 comments:

Anand said...

What to do if both arrays are of unequal length?

Anand said...

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


Admin said...

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

anshul said...

why dont you dynamically allocate array and change the address

Mahendran said...

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

Mahendran said...

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

Unknown said...

can't we write the program with out using swap keyword using pointers

கார்த்திக் said...

#include
#include
#include
int b[10],a[10],n,g,i,u;
void dd(int);
void main()
{
clrscr();
printf("enter ");
scanf("%d",&n);
if(n==0)
{
printf("please enter valid array");
goto g;
}
for(i=0;ig)
{
for(i=g;i<n;i++)
b[i]=a[i];
}
for(i=0;i<g;i++)
printf("\n%d",a[i]);
for(i=0;i<n;i++)
printf("\n%d",b[i]);
g:
getch();
}
void dd(int u)
{
if(a[i]!=0)
{
b[i]=a[i];
a[i]=u;
}
else
a[i]=b[i];
}

Unknown said...

if arrays are of un equal size then you just no need to mention its size

like:
int a[10]
int b[10]
answer to you is :
int a[size]
int b[size]

joel said...

How can numbers between two arrays be swapped with their positions?

Unknown said...

Accept two different arrays and interchange it

Unknown said...

Please help me to find the answer