write a program to assign 5 and 6 two variables A and B respectively and interchange them after interchanging A and B will be 6 and 5 respectively in html
Answers
Answer:
program to swap two numbers with and without using third variable, using pointers, functions (Call by reference) and using bit-wise XOR operator. Swapping means interchanging. If the program has two variables a and b where a = 4 and b = 5, after swapping them, a = 5, b = 4. In the first C program, we use a temporary variable to swap two numbers.
Swapping of two numbers in C
#include <stdio.h>
int main()
{
int x, y, t;
printf("Enter two integers\n");
scanf("%d%d", &x, &y);
printf("Before Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
t = x;
x = y;
y = t;
printf("After Swapping\nFirst integer = %d\nSecond integer = %d\n", x, y);
return 0;
}
Download Swap numbers program.
The output of the program:
Enter two integers
23
45
Before Swapping
First integer = 23
Second integer = 45
After Swapping
First integer = 45
Second integer = 23
Swapping of two numbers without third variable
You can also swap two numbers without using third variable. In this case C program will be as follows:
#include <stdio.h>
int main()
{
int a, b;
printf("Input two integers (a & b) to swap\n");
scanf("%d%d", &a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %d\nb = %d\n",a,b);
return 0;
}