Social Icons

Saturday, December 8, 2012

C Program to swap two integers

 To start with the program, first its good to understand about swapping. Its possible that many people may not aware of this term. If you know, its good. Swap means interchange. Swap two numbers means to interchange the values of two numbers from each other. Suppose, x=15 and y=20. Then after swapping it will be x=20 and y=15. We have to write the program for the same. So, here we go:

                #include<stdio.h>
                void main()
                {
                       int x, y, temp;
                       printf("Enter two numbers");
                       scanf("%d%d",&x,&y);
                       printf("Before swapping, x=%d and y = %d \n",x,y);
                       temp = x;
                       x = y;
                       y = temp;
                       printf("After swapping, x=%d and y = %d",x,y);
               }

Ouptut: Before swapping, x=15 and y=20    (15 and 20 are the examples.. lets say these values are entered by user)
                 After Swapping, x=20 and y=15

Explanation for the program
                  Here, x and y are the two variables between which swapping has to be done. But, if we do first x=y. It means that value of y will be stored to x. But, now we have to get value of x stored in y. But, now its not possible because original value of x is lost as it holds now value of y. So, here we have used a third variable called temp(or say temporary). In this variable, firstly we have stored the value of x so that original value of x is not lost and then this value is assigned to y. In this way, these numbers are swapped.
                  Now, lets say you do it(swapping) without using third variable('temp' here). Wondering how is it possible. No need to wonder more... Here, I see you, how to do it???

WAP to swap two numbers without using third variable
        #include<stdio.h>
        void main()
        {
            int x,y;
            printf("Enter the two numbers to swap:");
            scanf("%d%d",&x,&y);
            printf("Before Swapping: x=%d \n y=%d \n",x,y);
            x = x+y;
            y = x-y;
            x=x-y;
            printf("After Swapping: x=%d \n y=%d \n",x,y);
        }
 Output:- Before swapping: x=15
                                                        y=20
                   After swapping: x=20
                                                    y=15
Explanation for the program
              Suppose we have two variables as x=15 and y=20. Now, according to the program  x = x+y;   => x = 15+20   => x = 35  y = x-y;    => y = 35-20    => y=15  x = x-y;    => x = 35-15    => x=20So, finally we get x=20 and y=15 which are the swapped values....

No comments:

Post a Comment

Total Pageviews