不使用临时变量交换两个数组。在这里,我们将使用算术运算符和位运算符而不是第三个变量。
读取第一个数组的逻辑如下所示:-
printf("enter first array ele:
");for(i = 0; i < size; i++){ scanf("%d", &first[i]);}
读取第二个数组的逻辑如下 −
printf("enter first array ele:
");for(i = 0; i < size; i++){ scanf("%d", &first[i]);}
不使用第三个变量交换两个数组的逻辑如下 −
for(i = 0; i < size; i++){ first[i] = first[i] + sec[i]; sec[i] = first[i] - sec[i]; first[i] = first[i] - sec[i];}
程序以下是在不使用临时变量的情况下交换两个数组的c程序:
在线演示
#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:
"); for(i = 0; i < size; i++){ scanf("%d", &first[i]); } printf("enter second array ele:
"); 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("
first array after swapping %d elements
", size); for(i = 0; i < size; i ++){ printf(" %d \t ",first[i]); } printf("sec array after swapping %d elements
", size); for(i = 0; i < size; i ++){ printf(" %d \t ",sec[i]); } return 0;}
输出当上述程序被执行时,它产生以下结果 −
enter the size of array:5enter first array ele:11 12 13 14 15enter second array ele:90 80 70 60 50first array after swapping 5 elements90 80 70 60 50sec array after swapping 5 elements11 12 13 14 15
以上就是如何在c语言中不使用临时变量交换两个数组的值?的详细内容。