Home » C solved programs » C basic programs

C program to swap two numbers using four different methods



In this C program, we are going to learn how to swap two integer numbers using different methods; here we are going to use four different methods?

Given two integer numbers and we have to swap them using different methods in C language.

The methods that we are going to use in this program are:

  1. Using third variable
  2. Without using third variable
  3. Using X-OR operator
  4. Using simple statement
//C program to swap two numbers using four different methods.
 
#include <stdio.h>
 
int main()
{
    int a,b,t;
    printf(" Enter value of A ?  ");
    scanf("%d",&a);
    printf(" Enter value of B ?  ");
    scanf("%d",&b);
     
    printf("\n Before swapping : A= %d, B= %d",a,b);
 
    /****first method using third variable*/
    t=a;
    a=b;
    b=t;
    printf("\n After swapping (First method) : A= %d, B= %d\n",a,b);
 
    /****second method without using third variable*/
    a=a+b;
    b=a-b;
    a=a-b;
    printf("\n After swapping (second method): A= %d, B= %d\n",a,b);
 
    /****Third method  using X-Or */
    a^=b;
    b^=a;
    a^=b;
    printf("\n After swapping (third method) : A= %d, B= %d\n",a,b);
 
    /****fourth method  (single statement)*/
    a=a+b-(b=a);
    printf("\n After swapping (fourth method): A= %d, B= %d\n",a,b);
 
    return 0;
}

Output

Enter value of A ?  100
Enter value of B ?  200

Before swapping : A= 100, B= 200
After swapping (First method) : A= 200, B= 100

After swapping (second method): A= 100, B= 200

After swapping (third method) : A= 200, B= 100

After swapping (fourth method): A= 100, B= 200





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.