All for Joomla All for Webmasters

C Program to swap two numbers without third variable

We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:

  1. By + and –
  2. By * and /

Program 1: Using + and –

Let’s see a simple c example 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. a=a+b;//a=30 (10+20)
  9. b=a-b;//b=10 (30-20)
  10. a=a-b;//a=20 (30-10)
  11. printf(“\nAfter swap a=%d b=%d”,a,b);
  12. getch();
  13. }

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. a=a*b;//a=200 (10*20)
  9. b=a/b;//b=10 (200/20)
  10. a=a/b;//a=20 (200/10)
  11. printf(“\nAfter swap a=%d b=%d”,a,b);
  12. getch();
  13. }

Output:

Before swap a=10 b=20
After swap a=20 b=10
PinIt
submit to reddit

Leave a Reply

Top