Write C program to swap two numbers using pointers


Introduction

I have used Code::blocks 12 compiler for debugging purpose. But you can use any C programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Write C program to swap two numbers using pointers


  1. #include<stdio.h>
  2.  
  3. //Swap function to swap 2 numbers
  4. void swap(int *num1, int *num2) {
  5. int temp;
  6. //Copy the value of num1 to some temp variable
  7. temp = *num1;
  8.  
  9. //Copy the value of num2 to num1
  10. *num1 = *num2;
  11.  
  12. //Copy the value of num1 stored in temp to num2
  13. *num2 = temp;
  14. }
  15.  
  16. int main() {
  17. int num1, num2;
  18.  
  19. //Inputting 2 numbers from user
  20. printf("\nEnter the first number : ");
  21. scanf("%d", &num1);
  22. printf("\nEnter the Second number : ");
  23. scanf("%d", &num2);
  24.  
  25. //Passing the addresses of num1 and num2
  26. swap(&num1, &num2);
  27.  
  28. //Printing the swapped values of num1 and num2
  29. printf("\nFirst number : %d", num1);
  30. printf("\nSecond number : %d", num2);
  31.  
  32. return (0);
  33. }
  34.  
  35.  

Result

C language

     





Related Topics




Popular Posts