Q:

C program to swap two numbers using four different methods

0

C program to swap two numbers using four different methods

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Program:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C programming Basic Input, Output, if else, Ternary Operator based Programs

Similar questions


need a help?


find thousands of online teachers now
C program to check a given character is alphanumer... >>
<< C program to print ASCII table/chart...