In this tutorial, you will learn how to write a program to swap values using a third variable and a for-loop.
Our problem statement
Here we are taking two variables a and b and swapping their values with the help of a third variable.
For Example:
Input: a=45 and b=56
Output: a=56 and b=45
In the below program, the third variable ‘c’ acts as a temporary placeholder. When iterating using for-loop values for the variables are temporarily kept in ‘c’ variable.
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter the values of a and b: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
temp = a;
for (int i = 0; i < 1; i++) {
a = b;
b = temp;
}
printf("After swapping: a = %d, b = %d", a, b);
return 0;
}
Output:
Enter the values of a and b: 45
56
Before swapping: a = 45, b = 56
After swapping: a = 56, b = 45