×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous 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?

Problem statement

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

Methods

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

//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

C Basic Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.