Monday, May 23, 2016

How to swap two numbers in C Language

Swapping of two numbers in C Language

Using Two Variable:

Program 1:

#include<stdio.h>
#define SWAP(a,b) (a)^=(b)^=(a)^=(b)
void main()
{
int a,b;
a=12; b=17;
SWAP(a,b);
printf("a=%i,b=%i",a,b);
}

Program 2:

#include<stdio.h>
void main()
{
int a,b;
a=12; b=17;
a=a+b;
b=a-b;
a=a-b;
printf("a=%i,b=%i",a,b);
}

Using Third Variable:

#include<stdio.h>
void main()
{
int a,b,temp;
a=12; b=17; temp=0;
temp=a;
a=b;
b=temp;
printf("a=%i,b=%i",a,b);
}

No comments:

Post a Comment