Showing posts with label Swap two numbers. Show all posts
Showing posts with label Swap two numbers. Show all posts
Swap two numbers without Using third variable in C

Swap two numbers without Using third variable in C

Swap two numbers without Using third variable in C

In this program we will swap two numbers without using third variable. Lets understand common ways to swap two numbers without using third variable:
  1. By + and -
  2. By * and /

First we will learn swapping of two numbers

Program 1: Using Third Variable 

Let's write a program in C to swap two numbers using third variable.

  1. #include <stdio.h>
  2. int main()
  3. {
  4.       double firstNumber, secondNumber, temporaryVariable;

  5.       printf("Enter first number: ");
  6.       scanf("%lf", &firstNumber);

  7.       printf("Enter second number: ");
  8.       scanf("%lf",&secondNumber);

  9.       // Value of firstNumber is assigned to temporaryVariable
  10.       temporaryVariable = firstNumber;

  11.       // Value of secondNumber is assigned to firstNumber
  12.       firstNumber = secondNumber;

  13.       // Value of temporaryVariable (which contains the initial value of firstNumber) is assigned to secondNumber
  14.       secondNumber = temporaryVariable;

  15.       printf("\nAfter swapping, firstNumber = %.2lf\n", firstNumber);
  16.       printf("After swapping, secondNumber = %.2lf", secondNumber);

  17.       return 0;
  18. }
Output:
Before swap a=10 b=20
After swap a=20 b=10

Program 1: Using + and -

Let's write a program in C to swap two numbers without using third variable.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. main()  
  4. {  
  5. int a=10, b=20;    
  6. clrscr();    
  7. printf("Before swap a=%d b=%d",a,b);    
  8.   
  9. a=a+b;//a=30 (10+20)  
  10. b=a-b;//b=10 (30-20)  
  11. a=a-b;//a=20 (30-10)  
  12.   
  13. printf("\nAfter swap a=%d b=%d",a,b);  
  14. getch();  
  15. }  
Output:
Before swap a=10 b=20
After swap a=20 b=10

Program 2: Using * and /

Let's see another example to swap two numbers using * and /.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. main()  
  4. {  
  5. int a=10, b=20;    
  6. clrscr();    
  7. printf("Before swap a=%d b=%d",a,b);    
  8.   
  9. a=a*b;//a=200 (10*20)  
  10. b=a/b;//b=10 (200/20)  
  11. a=a/b;//a=20 (200/10)  
  12.   
  13. printf("\nAfter swap a=%d b=%d",a,b);   
  14. getch();  
  15. }  
Output:
Before swap a=10 b=20
After swap a=20 b=10

Popular Posts