C program to swap to numbers with and without using third variable


                  Swapping means to exchange two numbers with each others. For example before swapping no1=23 and no2= 45 but after swapping it will be no1=45 and no2=23. This swapping perform with or without using 3rd variable.


C Program for Swap Two Variable Using Third variable


#include<stdio.h>

void main()
{
       int no1,no2,temp;
       temp=0;
       clrscr();

       printf("Enter no1::");
       scanf("%d",&no1);

       printf("Enter no2::");
       scanf("%d",&no2);

       printf("Before swapping::\n");
       printf("no1::%d\n",no1);
       printf("no2::%d\n",no2);

       temp=no1;
       no1=no2;
       no2=temp;

       printf("After swapping::\n");
       printf("No1::%d\n",no1);
       printf("No2::%d",no2);
       getch();
}



c program to swap to numbers with or without using temp variable


C program to swap two variable without third variable


 Here we using another logic to swap two numbers as follow.
                    no1=no1+no2;
                    no2=no1-no2;
                    no1=no1-no2;



#include<stdio.h>

void main()
{
       int no1,no2;
       clrscr();

       printf("Enter no1::");
       scanf("%d",&no1);

       printf("Enter no2::");
       scanf("%d",&no2);

       printf("Before swapping::\n");
       printf("no1::%d\n",no1);
       printf("no2::%d\n",no2);

       no1=no1+no2;
       no2=no1-no2;
       no1=no1-no2;

       printf("After swapping::\n");
       printf("No1::%d\n",no1);
       printf("No2::%d",no2);
       getch();
}


swapping

Download


1 comments: