ADVERTISEMENT
Swap Two Numbers Without Using 3rd Variable
This C program takes two integer inputs, ‘a’ and ‘b’, and swaps their values without using a temporary variable.
#include<stdio.h>
main()
{
int a,b;
printf("Enter a\n");
scanf("%d",&a);
printf("Enter b\n");
scanf("%d",&b);
printf("The values of a is %d and b is %d before swaping\n",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("The values of a is %d and b is %d after swaping\n",a,b);
}
C Programming ExamplesOUTPUT
Enter a
6
Enter b
3
The values of a is 6 and b is 3 before swaping
The values of a is 3 and b is 6 after swapingC Programming ExamplesExplanation:
Here’s a step-by-step explanation of the code:
Header File:
- The program includes the standard C library header <stdio.h>, which is required for input and output operations.
Main Function:
- The main function is the entry point of the program, where the execution starts.
Variable Declarations:
- The program declares two integer variables, ‘a’ and ‘b’, to store the values provided by the user.
User Input:
- The program prompts the user to enter the value of ‘a’ with the message “Enter a” and waits for the user’s input.
- The scanf function is used to read the input, and the value is stored in the variable ‘a’.
- Similarly, the program prompts the user to enter the value of ‘b’ and reads the input, storing it in the variable ‘b’.
Display Values Before Swapping:
- The program uses printf to display the values of ‘a’ and ‘b’ before swapping.
- The message “The values of a is %d and b is %d before swaping” is used to display the values of ‘a’ and ‘b before swapping. The placeholders %d are replaced with the actual values of ‘a’ and ‘b when the printf function is executed.
Swapping Without a Temporary Variable:
The code performs the swap without using a temporary variable through the following steps:
- a = a + b: The value of ‘a’ is updated by adding it to ‘b’.
- b = a – b: The value of ‘b’ is updated by subtracting ‘b’ from the updated ‘a’. At this point, ‘a’ holds the sum of the original ‘a’ and ‘b’.
- a = a – b: The value of ‘a’ is updated by subtracting the updated ‘b’ from the sum of ‘a’ and ‘b’. Now, ‘b’ holds the original value of ‘a’ and ‘a’ holds the original value of ‘b’, effectively swapping their values.
Display Values After Swapping:
- The program uses printf once again to display the values of ‘a’ and ‘b after swapping.
- The message “The values of a is %d and b is %d after swaping” is used to display the updated values of ‘a’ and ‘b after swapping.
End of Program:
- After displaying the swapped values, the program reaches the end of the main function and, consequently, the end of the program’s execution.
This code allows the user to enter two integer values, ‘a’ and ‘b’, and then swaps their values without using a temporary variable. It demonstrates a common method for swapping variables in programming.