
不使用临时变量交换两个数组。在这里,我们将使用算术运算符和位运算符而不是第三个变量。
读取第一个数组的逻辑如下所示:-
printf("enter first array ele:</p><p>");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
}读取第二个数组的逻辑如下 −
printf("enter first array ele:</p><p>");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
}不使用第三个变量交换两个数组的逻辑如下 −
立即学习“C语言免费学习笔记(深入)”;
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:</p><p>");
for(i = 0; i < size; i++){
scanf("%d", &first[i]);
}
printf("enter second array ele:</p><p>");
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("</p><p> first array after swapping %d elements</p><p>", size);
for(i = 0; i < size; i ++){
printf(" %d \t ",first[i]);
}
printf("sec array after Swapping %d elements</p><p>", 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
以上就是如何在C语言中不使用临时变量交换两个数组的值?的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号