Hoán đổi hai mảng mà không cần sử dụng biến Temp. Ở đây, chúng ta sẽ sử dụng Toán tử số học và Toán tử Bitwise thay vì biến thứ ba.
Logic để đọc mảng đầu tiên như sau -
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
} Logic để đọc mảng thứ hai như sau -
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
} Lôgic để hoán đổi hai mảng mà không sử dụng biến thứ ba như sau -
for(i = 0; i < size; i++){
first[i] = first[i] + sec[i];
sec[i] = first[i] - sec[i];
first[i] = first[i] - sec[i];
} Chương trình
Sau đây là chương trình C để hoán đổi hai mảng mà không cần sử dụng biến Temp -
#include<stdio.h>
int main(){
int size, i, first[20], sec[20];
printf("enter the size of array:");
scanf("%d", &size);
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
}
printf("enter second array ele:\n");
for(i = 0; i < size; i ++){
scanf("%d", &sec[i]);
}
//Swapping two Arrays
for(i = 0; i < size; i++){
first[i] = first[i] + sec[i];
sec[i] = first[i] - sec[i];
first[i] = first[i] - sec[i];
}
printf("\n first array after swapping %d elements\n", size);
for(i = 0; i < size; i ++){
printf(" %d \t ",first[i]);
}
printf("sec array after Swapping %d elements\n", size);
for(i = 0; i < size; i ++){
printf(" %d \t ",sec[i]);
}
return 0;
} Đầu ra
Khi chương trình trên được thực thi, nó tạo ra kết quả sau -
enter the size of array:5 enter first array ele: 11 12 13 14 15 enter second array ele: 90 80 70 60 50 first array after swapping 5 elements 90 80 70 60 50 sec array after Swapping 5 elements 11 12 13 14 15