Exchange two arrays without using temporary variables. Here we will use arithmetic and bitwise operators instead of the third variable.
The logic of reading the first array is as follows:-
printf("enter first array ele:</p><p>"); for(i = 0; i < size; i++){ scanf("%d", &first[i]); }
The logic of reading the second array is as follows-
printf("enter first array ele:</p><p>"); for(i = 0; i < size; i++){ scanf("%d", &first[i]); }
Do not use the third variable exchange The logic of the two arrays is as follows −
for(i = 0; i < size; i++){ first[i] = first[i] + sec[i]; sec[i] = first[i] - sec[i]; first[i] = first[i] - sec[i]; }
The following is a C program to exchange two arrays without using temporary variables:
Online demonstration
#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; }
When the above program is executed, it produces the following results −
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
The above is the detailed content of How to exchange the values of two arrays in C language without using temporary variables?. For more information, please follow other related articles on the PHP Chinese website!