Progm
Progm
1 #include<stdio.h> 2 main() 3 { 4 int a, b; 5 printf("Enter two numbers : "); 6 scanf("%d%d",&a,&b); 7 8 a = a + b; 9 b = a - b; 10 a = a - b; 11 12 printf("a = %d\nb = %d\n",a,b); 13 14 } Program To Swap Two Values With Temp Variable Program to Swaping two values */ #include<stdio.h> #include<conio.h> void main() { int a, b, temp; clrscr(); printf("\n Enter the value of a "); scanf("%d",&a); printf("\n Enter the value of b "); scanf("%d",&b); temp=a; a=b; b=temp; printf("\n a = %d , b = %d",a,b); getch(); }
Question: The usual method of swapping two numbers, using a temporaty variable is as shown below.
// Swapping 2 int, X & Y using temporary variable t int t = X; X = Y; Y = t;
How will you swap two numbers without using a temporary variable? Solution:
The disadvantage of this method is that it can only be applied to low-level data types like integers & characters (char, short, int, long). C & C++ does not allow bit-wise operation on non-integral operands. Using +,- operators
X = X + Y; Y = X - Y; X = X - Y;
This method can only be applied on numerical values. The issue of arithmetic overflow will also be there.