We will see two programs to swap two numbers. In the first program we are swapping two numbers using a temporary variable and in the second program, we are swapping the numbers without using a temporary variable.
Example 1: Program to swap numbers using a temp variable
In this program we are using a temporary variable temp
. The logic we are using for swapping is:
1. Assigning the value of num1 (this contains the first number) to the temp variable to create the backup of first number.
2. Assigning the value of second variable(this contains the second number) to the variable num1.
3. Assigning the value of temp variable(this has the first number) to the variable num2.
#include <stdio.h> int main() { double num1, num2, temp; //Storing first number entered by user in num1 printf("Enter First Number: "); scanf("%lf", &num1); //Storing second number entered by user in num2 printf("Enter Second Number: "); scanf("%lf",&num2); printf("Before swapping:\n"); //%.2lf is to have two digits after the decimal point printf("num1 is: %.2lf and num2 is: %.2lf\n", num1, num2); // Assigning the value of num1 to the temp variable temp = num1; // Assigning the value of second number num2 to num1 num1 = num2; /* Assigning the value of temp variable(which is the * original value of num1) to the num2 */ num2 = temp; printf("After swapping:\n"); printf("num1 is: %.2lf and num2 is: %.2lf", num1, num2); return 0; }
Output:
Enter First Number: 89.99 Enter Second Number: 13.65 Before swapping: num1 is: 89.99 and num2 is: 13.65 After swapping: num1 is: 13.65 and num2 is: 89.99
Example 2: Swapping two numbers without using temporary variable
In this program, we are not using a temporary variable for swapping the values of two numbers.
#include <stdio.h> int main() { double num1, num2; //Storing first number entered by user in num1 printf("Enter First Number: "); scanf("%lf", &num1); //Storing second number entered by user in num2 printf("Enter Second Number: "); scanf("%lf",&num2); printf("Before swapping:\n"); printf("num1 is: %.2lf and num2 is: %.2lf\n", num1, num2); /* This logic swaps the values of num1 and num2 * without using a temporary variable. */ num1 = num1 - num2; num2 = num1 + num2; num1 = num2 - num1; printf("After swapping:\n"); printf("num1 is: %.2lf and num2 is: %.2lf", num1, num2); return 0; }
Output:
Enter First Number: 77.77 Enter Second Number: 19.51 Before swapping: num1 is: 77.77 and num2 is: 19.51 After swapping: num1 is: 19.51 and num2 is: 77.77
Check out these related Programs:
Leave a Reply