Showing posts with label Swap numbers. Show all posts
Showing posts with label Swap numbers. Show all posts

Tuesday, 19 March 2019

C program to swap two numbers using bit-wise XOR (method 3)

Swapping is used in sorting algorithms like in bubble sort,that is when we wish to arrange numbers in a particular order either in ascending order or in descending order.
Problem:
Given two numbers num1=a and num2=b, task is exchange values of these numbers i.e num1=b and num2=a;

Method 3: Using bit-wise XOR
#include<stdio.h>
int main(){
    int num1=10,num2=20;
    void swapXOR(int,int);  //function prototype
   printf("Values before swapping by call by value:num1=%d,num2=%d.\n",num1,num2);
    swapXOR (num1,num2);    
    return 0;
}
//function definition : using bitwise XOR operator
void swapXOR (int n1,int n2){
  n1 = n1 ^ n2;
  n2 = n1 ^ n2;
  n1 = n1 ^ n2;
  printf("Inside swap3 : num1=%d,num2=%d\n",n1,n2);
}
Output:
Please comment if you find anything incorrect, or you want to improve the topic discussed above.

C program to swap two numbers without using temporary variable(method 2)

Swapping is used in sorting algorithms like in bubble sort,that is when we wish to arrange numbers in a particular order either in ascending order or in descending order.
Problem:
Given two numbers num1=a and num2=b, task is exchange values of these numbers i.e num1=b and num2=a;
Method 2: Without using third variable
#include<stdio.h>
int main(){
    int num1=10,num2=20;
    void swapWithoutTemp (int,int);  //function prototype
   printf("Values before swapping by call by value: num1=%d,num2=%d.\n",num1,num2);
    swapWithoutTemp (num1,num2);     
    return 0;
}
//function definition : without using third variable
void swapWithoutTemp(int n1,int n2){
  n1=n1+n2;
  n2=n1-n2;
  n1=n1-n2;
  printf("Inside swap2 : num1=%d,num2=%d\n",n1,n2);
}


Output:
Please comment if you find anything incorrect, or you want to improve the topic discussed above.

C program to swap two numbers using temporary variable(method 1)

Swapping is used in sorting algorithms like in bubble sort,that is when we wish to arrange numbers in a particular order either in ascending order or in descending order.
Problem:
Given two numbers num1=a and num2=b, task is exchange values of these numbers i.e num1=b and num2=a;
Method 1: Using third variable
#include<stdio.h>
int main(){
    int num1=10,num2=20;
    void swapUsingTemp(int,int);  //function prototype
   printf("Values before swapping by call by value: num1=%d,num2=%d.\n",num1,num2);
    swapUsingTemp (num1,num2);
    return 0;
}
//function definition: using third variable
void swapUsingTemp (int n1,int n2){
  int temp;
  temp=n1;
  n1=n2;
  n2=temp;
  printf("Inside swap1 : num1=%d,num2=%d\n",n1,n2);
}
Output:
Please comment if you find anything incorrect, or you want to improve the topic discussed above.