สลับค่าอาร์เรย์ 2 ชุดโดยไม่ใช้ Temp variable ใช้ Arithmetic Operators แทน
ตรรกะการสลับแบบไม่ใช้ตัวแปรกลาง
for(i = 0; i < size; i++) {
first[i] = first[i] + sec[i];
sec[i] = first[i] - sec[i];
first[i] = first[i] - sec[i];
}
โปรแกรมตัวอย่าง
#include <stdio.h>
int main() {
int size, i;
int first[20], sec[20];
printf("Enter array size: ");
scanf("%d", &size);
printf("Enter first array elements:\n");
for(i = 0; i < size; i++) scanf("%d", &first[i]);
printf("Enter second array elements:\n");
for(i = 0; i < size; i++) scanf("%d", &sec[i]);
// Swapping without temp variable
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("\nFirst array after swap: ");
for(i = 0; i < size; i++) printf("%d ", first[i]);
printf("\nSecond array after swap: ");
for(i = 0; i < size; i++) printf("%d ", sec[i]);
return 0;
}
ผลลัพธ์
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