Swap numbers

C program to swap the numbers without using third variable :

code

  #include<stdio.h>

#include<conio.h>

   void main()

{

  int  a,b;

   clrscr();

   printf(“\nEnter  first number :”);

   scanf(“%d”, &a);

   printf(“\nEnter second number :”);

   scanf(“%d”,&b);

   printf(“\nNumber before swap\n a = %d\n b = %d”,a,b);

   a=a+b;

  b=a-b;

  a=a-b;

  printf(“\n Number after swapping :”);

  printf(“a= %d\n, b= %d”,a,b);

  getch();

}


output

Enter first number :

2

Enter second number :

5

Number before swap :

a=2

b=5

Number after swap :

a=5

b=2

 

 



C program to swap the numbers using third variable :

code

  #include<stdio.h>

#include<conio.h>

   void main()

{

    int  a,b,temp;

     clrscr();

     printf(“\nEnter  first number :”);

   scanf(“%d”, &a);

   printf(“\nEnter second number :”);

   scanf(“%d”,&b);

   printf(“\nNumber before swap\n a = %d\n b = %d”,a,b);

   temp=a;

  a=b;

   b=temp;

 printf(“\n Number after swapping :”);

 printf(“a= %d\n, b= %d”,a,b);

  getch();

}


output

Enter first number :

2

Enter second number :

5

Number before swap :

a=2

b=5

Number after swap :

a=5

b=2


 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s