3) Swapping two numbers without using a temporary variable
void main()
{
int a,b;
printf("enter any 2 nums to swap");
scanf("%d%d",&a,&b);
printf("\n nums before swapping are a=%d and b=%d",a,b);
int a,b;
printf("enter any 2 nums to swap");
scanf("%d%d",&a,&b);
printf("\n nums before swapping are a=%d and b=%d",a,b);
a=a+b; //statement 1
b=a-b; //statement 2
a=a-b; //statement 3
printf("\n nums after swapping are a=%d and b=%d\n",a,b);
}
Lets Take an Example and try to solve see how it really works
lets say a=2,b=3;
statement 1
a=a+b now lets substitute our values and try to evaluate the expression
a=2+3
So at the end of the statement 1 a's value is 5
statement 2
b=a-b;
b=5-3
b=2
So at the end of the statement 2 b's value is 2
statement 3
a=a-b
a= 5-2 ( remember a's value is still 5 from our first statement)
So at the end of the statement a's value is 3
Mission Accomplished now a=3 and b=2
________________________________________________________________________________
No comments:
Post a Comment