// Write a C program to swap two numbers using third variable.
#include<stdio.h>
int main(){
int a, b, temp;
printf("Enter the value of a : ");
scanf("%d", &a);
printf("Enter the value of b : ");
scanf("%d", &b);
// Before swapping the value of a and b.
printf("Before Swapping the value of a = %d\tb = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
// using temp to swap storing a to temp and b to a then moving temp to b.
// After swapping the value of a and b.
printf("\nAfter Swapping the value of a = %d\tb = %d", a, b);
return 0;
}
The above code is swap two number given from the user. In this program takes input from the user a and b using the scanf() function and swap two numbers.
#include<stdio.h>
The above line of code includes the standard input/output library which is used to display the output and takes input from the user.
int main() {
Every program start from the main function(). The main() is the entry point for all programs.
int a, b, temp;
Declares the three integer variables named a, ,b and temp.
printf("Enter the value of a : ");
Prompt or message to the user to enter the value of a.
scanf("%d", &a);
Read the value for a using the scanf() function from the user.
printf("Enter the value of b : ");
Prompt to the user to enter the value of b using printf() function.
scanf("%d", &b);
Read the value of b from the user using the scanf() function.
printf("Before Swapping the value of a = %d\tb = %d\n", a, b);
Prompt or display the Before swapping the value of a and b using printf() function.
a = a + b;
b = a - b;
a = a - b;
These lines of code swap the number to each other. a = a + b store the sum of value both numbers, b = a - b store the value of of a - b here a is the updated value use, a = a - b store the value of a - b here a and b are the updated value used. So after those steps the value swapped.
printf("\nAfter Swapping the value of a = %d\tb = %d", a, b);
Prompt to the user to After swapping the value of a and b.
return 0;
}
Program is successfully executed and returns the value 0.
// Pseudocode
1. Start
2. Declare a, b, and c as integers.
3. Display "Enter the value of a : "
4. Read input for a using scanf()
5. Display "Enter the value of b : "
6. Read input for b using scanf()
7. Display "Before Swapping the value of a and b"
8. a = a + b;
9. b = a - b;
10. a = a - b;
11. Display "After swapping the value of a and b"
12. End
Comments
Oops!