Home C Programming Episode 13: Swapping Number

Episode 13: Swapping Number

0
SHARE

Explanation:

Swapping is very easy concept. Take a 2 value lets say first number is 12 and second number is 10. Now swap it that means first number will be 10 and second will be 12.

What is the logic behind it?

There are two logic behind it, one is using two variable and another is using three variable.

Three variable logic:

Take a value A and Take a value B, Take another variable Temp. // A=10 B=20

Now copy the value A in Temp.// Temp=10

Copy the value B in variable A.//A=20

Copy the value of Temp in Variable B.//B=10

Two variable logic:

Take a value A and Take a value B. //A=10 B=20

A=A+B //A=10+20

B=A-B //B=30-20 =10

A=A-B //A=30-10=20

code:

Swapping using 3 variable:

#include <stdio.h>
#include <conio.h>
void main()
{
int a,b,temp;

printf(“Enter the First value:\t”);
scanf(“%d”,&a);

printf(“Enter the second value:\t”);
scanf(“%d”,&b);

printf(“\n\nOriginal Numbers are First: %d Second: %d”,a,b);
temp=a;
a=b;
b=temp;

printf(“\nSwapped Numbers are First: %d Second: %d”,a,b);
getch();

}

 

Swapping using 2 variable:

void main()
{
int a,b;
printf(“Enter the First value:\t”);
scanf(“%d”,&a);

printf(“Enter the second value:\t”);
scanf(“%d”,&b);

printf(“\n\nOriginal Numbers are First: %d Second: %d”,a,b);

a=a+b;
b=a-b;
a=a-b;

printf(“\nSwapped Numbers are First: %d Second: %d”,a,b);
getch();

}

Output:

Enter the First value: 10
Enter the second value: 30
Original Numbers are First: 10 Second: 30
Swapped Numbers are First: 30 Second: 10

LEAVE A REPLY

Please enter your comment!
Please enter your name here