Swapping of two numbers using c language


              To interchange, the value of two variables is known as swapping.
              Example:- Before execution a=2, b=3
                                After execution a=3, b=2

     #include <stdio.h>
  int main()
   {
    int a,b,c;
    printf("Enter value for a\n");
    scanf("%d",&a);
    printf("Enter value for b\n");
    scanf("%d",&b);
    c=a;
    a=b;
    b=c;
    printf("After swapping a=%d b=%d",a,b);
    return 0;   
   }


output: Enter value for a
               10
               Enter value for b
               20
               After swapping a=22 b=11

  swapping of two number without using third variable

      on the above example, we need a third variable c to store the value temporarily but here the following c program only need two variable to swap the values.

   #include <stdio.h>
   int main()
    {
     int a,b;
     printf("Enter value for a\n");
     scanf("%d",&a);
     printf("Enter value for b\n");
     scanf("%d",&b);
     a=a+b;
     b=a-b;
     a=a-b;
     printf("After swapping a=%d b=%d",a,b);
    }

output: Enter value for a
               11
               Enter value for b
               22
               After swapping a=22 b=11




No comments:

Post a Comment

For any doubt or suggestion you can write here