Swapping between two numbers

Program to swap two numbers.
Program to swap two numbers without using temporary variable.
Program to swap two numbers without using temporary variable and arithmetic operators.
Program to swap two numbers in single line.
//Swapping between two numbers.
#include<stdio.h>
int main() {
    int n1,n2,temp;
    scanf("%d %d",&n1,&n2);
    printf("Before swapping, n1 = %d \t n2 = %d",n1,n2);
    temp=n1;
    n1=n2;
    n2=temp;
    printf("\nAfter swapping, n1 = %d \t n2 = %d",n1,n2);
}
//Swapping between two numbers without using temporary variable.
#include<stdio.h>
int main() {
   int n1,n2,temp;
   scanf("%d %d",&n1,&n2);
   printf("Before swapping, n1 = %d \t n2 = %d",n1,n2);
   n1=n1+n2;        //or n1=n1*n2;
   n2=n1-n2;        //or n2=n1/n2;
   n1=n1-n2;        //or n1=n1/n2;
   printf("\nAfter swapping, n1 = %d \t n2 = %d",n1,n2);
}
//Swapping between two numbers without using temporary variable and arithmetic operators.
#include<stdio.h>
int main() {
   int n1,n2,temp;
   scanf("%d %d",&n1,&n2);
   printf("Before swapping, n1 = %d \t n2 = %d",n1,n2);
   n1=n1^n2;
   n2=n1^n2;
   n1=n1^n2;
   printf("\nAfter swapping, n1 = %d \t n2 = %d",n1,n2);
}
//Swapping between two numbers in single line.
#include<stdio.h>
int main() {
    int n1,n2;
    scanf("%d %d",&n1,&n2);
    printf("Before swapping, n1 = %d \t n2 = %d",n1,n2);
    n1=n1+n2-(n2=n1);
    printf("\nAfter swapping, n1 = %d \t n2 = %d",n1,n2);
}

No comments:

Post a Comment

Total Pageviews