C program to swap two numbers using a third variable - Source code
#include<stdio.h>
int main() {
int a, b, temp;
printf("Enter the value of a and b: \n");
scanf("%d %d", &a, &b);
printf("Before swapping a=%d and b=%d ", a, b);
/*Swapping starts here*/
temp = a;
a = b;
b = temp;
printf("\nAfter swapping a=%d and b=%d", a, b);
return 0;
}
Program Output
Enter the value of a and b:
100
45
Before swapping a=100 and b=45
After swapping a=45 and b=100
Program Explanation
1. In the above program, first, the temp variable is assigned the value of first number a.
2. Then, the value of first number a is assigned to second number(b).
3. Finally, the temp variable (which holds the initial value of a) is assigned to variable b, which completes the swapping process.
4. Note that, here, temp variable is used to hold the value of first variable a and doesn't have any other use except that.
C program to swap two numbers using a third variable - Source code
Program Output
Program Explanation
1. In the above program, first, the temp variable is assigned the value of first number a.
2. Then, the value of first number a is assigned to second number(b).
3. Finally, the temp variable (which holds the initial value of a) is assigned to variable b, which completes the swapping process.
4. Note that, here, temp variable is used to hold the value of first variable a and doesn't have any other use except that.
need an explanation for this answer? contact us directly to get an explanation for this answer