Write a program to swap two inputted integer numbers using third variable without using third variable
Write a program to swap two inputted integer numbers
-
using third variable
-
without using third variable
Write a program to swap two inputted integer numbers
using third variable
without using third variable
Best answer
Answer: Swap with a temporary variable (t = a; a = b; b = t;) or without one (a = a + b; b = a - b; a = a - b;).
Logic:
Program:
#include <stdio.h>
int main()
{
int a, b, t;
/* (i) Using a third variable */
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
t = a;
a = b;
b = t;
printf("After swapping (using third variable): a = %d, b = %d\n", a, b);
/* (ii) Without using a third variable */
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping (without third variable): a = %d, b = %d\n", a, b);
return 0;
}Sample output (actual run):
Enter two integers: 5 9
Before swapping: a = 5, b = 9
After swapping (using third variable): a = 9, b = 5
Enter two integers: 12 7
Before swapping: a = 12, b = 7
After swapping (without third variable): a = 7, b = 12Answer: two programs below swap two integers, one with a third variable and one without.
(a) Using a third variable
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
temp = a; /* save a */
a = b; /* copy b into a */
b = temp; /* old a into b */
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
(b) Without a third variable
#include <stdio.h>
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
a = a + b; /* a holds the sum */
b = a - b; /* (a+b) - b = old a */
a = a - b; /* (a+b) - old a = old b */
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
Example: input 5 and 9. In (b), a = 14, then b = 14 − 9 = 5, then a = 14 − 5 = 9. Output: a = 9, b = 5.
(The sum method can overflow for very large numbers; the XOR trick a ^= b; b ^= a; a ^= b; avoids that.)
Log in or create a free account to answer this question.