Write a c program to swap two numbers using third variable. Given two input integers, We have to write a code to swap two numbers using a third or temporary variable.
What is Swapping?
In swapping, we need to exchange the position of two elements.
For example – Let’s say initially the value of a and b is 12 and 15. After swapping the value of a and b is 15 and 12.
a = 12
b =15
After swapping
a = 15
b = 12
Algorithm to Swap Two Numbers using Third Variable
1. Declare three variables.
2. i) Assign the value of the first variable in temp.
ii) Then assign the value of the second variable into the first variable.
iii) Finally, assign the value of temp variable into the second variable.
Let’s declared three variables temp, a and b. Code logic to swap two numbers using third variable.
1 2 3 4 |
//Logic to swap two numbers using third variable temp = a; a = b; b = temp; |
C Program to swap two numbers without using third variable
Swap two numbers using a pointer
Swap two numbers using bitwise XOR operator
Programming questions on various topics for practice
C Program to Swap Two Numbers using Third Variable
We have understood how to swap two numbers using third variable. Let’s write a c code to implement them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <stdio.h> int main(void) { // Variable declaration int a, b, temp; printf("Enter two numbers a and b "); scanf("%d %d", &a, &b); // Swap logic temp = a; a = b; b = temp; printf("\n After swapping \na = %d\nb = %d\n", a, b); return 0; } |
C, C++ Programming Questions for Practice