C program Swapping two numbers

The process of Exchanging values of two variable is called swapping. The following two C program swap two numbers by calling the swap function by reference (address of variable). The first one swap two numbers with help of a temporary variable and latter one swap two number without a temporary variable.

       given two numbers  x =10  and y=15;

          swap(x,y)

       results  - print x=15 and y=10 

  

Swapping two numbers - C programming code

The c program swaps value of two variable x and y using a temporary variable. The value of the variable x and y are given as input and prints swapped value from the variables as the result.

 
#include <stdio.h>
void swap (int *x,int *y)  {

    int temp = *x;
 *x =*y;
 *y =temp;
}


int main() {

        int x=0,y=0; 
        printf("\n swap two numbers - call by reference");
 
 printf("\nEnter value for x :");
 scanf("%d",&x);
 
 printf("\nEnter value for y :");
 scanf("%d",&y);

 swap(&x,&y);

        printf("\nx value :%d ",x);
 printf("\ny value :%d ",y);
 
    return 0;
 }

swapping two numbers - output


 swap two numbers - call by reference

  Enter value x =12

  Enter value y =21

 Results :
  x =21
  y=12    
 

Swapping two numbers without temporary variable- C programming code

The c program swaps value of two variable x and y without using a temporary variable. The value of the variable x and y are given as input and prints swapped value from the variables as the result.

 
#include <stdio.h>
void swap (int *x,int *y)  {    
 *x =*x+*y;
 *y =*x - *y;
 *x =*x - *y;
}

int main() {

        int x=0,y=0; 
        printf("\n swap two numbers - call by reference");
 
 printf("\nEnter value for x :");
 scanf("%d",&x);
 
 printf("\nEnter value for y :");
 scanf("%d",&y);

 swap(&x,&y);
       printf("\n Results ");
       printf("\nx value :%d ",x);
       printf("\ny value :%d ",y);
 
    return 0;
 }
 

swapping two numbers - output


 swap two numbers - call by reference

  Enter value x =14

  Enter value y =121

 Results :
  x =121
  y=14    
 


Download c program source code


Comments

Popular posts from this blog

Hexadecimal to Binary Conversion

Binary to Decimal conversion -Bitwise Left shift Operator

Convert Octal to Binary