Write C++ program to swap two numbers using pointers


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


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

Result

C++ language techstudy.org

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.