C Tutorial
This c program is used to swap two integers value using arithmetic logic and without using the third variable
#include<stdio.h> void main() { int a, b; printf("Enter a: "); scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); printf("Before swap: a = %d, b = %d\n", a, b); a = a + b; b = a - b; a = a - b; printf("After Swap: b = %d, b = %d\n", a, b); }Output:
$ cc swap1.c $ ./a.out Enter a: 23 Enter b: 43 Before swap: a = 23, b = 43 After Swap: b = 43, b = 23
This c program is used to swap two integers value using bitwise XOR logic and without using the third variable
#include<stdio.h> void main() { int a, b; printf("Enter a: "); scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); printf("Before swap: a = %d, b = %d\n", a, b); a = a ^ b; b = a ^ b; a = a ^ b; printf("After Swap: b = %d, b = %d\n", a, b); }Output:
$ cc swap2.c $ ./a.out Enter a: 45 Enter b: 53 Before swap: a = 45, b = 53 After Swap: b = 53, b = 45
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page