C Code 13 _ To swap two numbers using third variable and with out using third variable



C Code 13 _ To swap two numbers using third variable and with out using third variable


Program:



#include<stdio.h>
int main()
{
                int a,b,temp,ch;
                printf("* * * * * * Swapping Two Numbers * * * * * * *");
                printf("\nCommonly there are two ways of swapping numbers : ");
                printf("\n1 - Swapping using Third variable ");
                printf("\n2 - Swapping with out using Third variable ");
                printf("\nEnter two integers : ");
                scanf("%d%d",&a,&b);
                printf("\nEnter your choice (1 or 2) , \n1 for trying swapping using third variable\n2 for with out using third variable : ");
                scanf("%d",&ch);
                switch(ch)
                {
                                case 1:
                                                //here we are using a temporary variable(temp) to swap two numbers.
                                                printf("\nValues before swapping : a = %d  b = %d ",a,b);
                                                temp=a;
                                                a=b;
                                                b=temp;
                                                printf("\nValues after swapping : a = %d  b = %d ",a,b);
                                                break;
                                               
                                case 2:
                                                //here we are using arithmetic operation to swap two numbers. 
                                                printf("\nValues before swapping : a = %d  b = %d ",a,b);
                                                a=a+b;
                                                b=a-b;
                                                a=a-b;
                                                printf("\nValues after swapping : a = %d  b = %d ",a,b);
                                                break;
                                               
                                default:
                                                printf("\nEnter either 1 or 2");
                }
                return 0;
}




Output:








Thank you ...

Popular Posts