m2skills

swap logic c

Mar 29th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | None | 0 0
  1. // program to swap 2 numbers using different methods
  2.  
  3. #include<stdio.h>
  4. #include<conio.h>
  5.  
  6. // method that swaps numbers using + and - operations  
  7. void swap1(int *num1, int *num2){
  8.     *num1 = *num1 + *num2;
  9.     *num2 = *num1 - *num2;
  10.     *num1 = *num1 - *num2;
  11.    
  12.     return;
  13. }
  14.  
  15. // method that swaps numbers using * and / operations
  16. void swap2(int *num1, int *num2){
  17.     *num1 = *num1 * *num2;
  18.     *num2 = *num1 / *num2;
  19.     *num1 = *num1 / *num2;
  20.    
  21.     return;
  22. }
  23.  
  24. // method that swaps numbers using ^ ( ex-or ) operations
  25. void swap3(int *num1, int *num2){
  26.     *num1 = *num1 ^ *num2;
  27.     *num2 = *num1 ^ *num2;
  28.     *num1 = *num1 ^ *num2;
  29.    
  30.     return;
  31. }
  32.  
  33. // method that swaps numbers using temp variables
  34. void swap4(int *num1, int *num2){
  35.     int temp;
  36.     temp = *num1;
  37.     *num1 = *num2;
  38.     *num2 = temp;
  39.    
  40.     return;
  41. }
  42.  
  43. void main(){
  44.    
  45.     int a = 10, b = 15;
  46.     float c = 10.999,d = 11.222;
  47.     printf("Values before swapping are a = %d and b = %d", a,b);
  48.    
  49.     swap1(&a, &b);
  50.     printf("\nValues after swapping using swap1 are :");
  51.     printf("\na = %d \nb = %d",a,b);
  52.    
  53.     swap2(&a, &b);
  54.     printf("\nValues after swapping using swap2 are :");
  55.     printf("\na = %d \nd = %d",a,b);
  56.    
  57.     swap3(&a, &b);
  58.     printf("\nValues after swapping using swap3 are :");
  59.     printf("\na = %d \nb = %d",a,b);
  60.    
  61.     swap4(&a, &b);
  62.     printf("\nValues after swapping using swap4 are :");
  63.     printf("\na = %d \nb = %d",a,b);
  64.    
  65.     return;
  66. }
Add Comment
Please, Sign In to add comment