首页 > 文章列表 > 如何在C语言中不使用临时变量交换两个数组的值?

如何在C语言中不使用临时变量交换两个数组的值?

C语言中的交换数组值
125 2023-08-30

不使用临时变量交换两个数组。在这里,我们将使用算术运算符和位运算符而不是第三个变量。

读取第一个数组的逻辑如下所示:-

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: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