-->





Translate

C++ program to swap two numbers using built in swap function from c++ standard library

1 comment

What is swapping?
It means exchange things with each other 
For more information have a look at swapping concept by Wikipedia

Calling Methods:
  1. swap();
  2. std:swap();

C++ code which take two numbers from user and swap using built in swap function. Program takes two input from user and displays numbers before and after swapping
  1. #include <iostream>
  2. using namespace std;
  3. void swap()
  4. {
  5.     cout<<"this is my swap";
  6. }
  7. int main()
  8. {
  9.     int firstNum , secondNum;
  10.     cout<<"Enter value for First Number:   ";
  11.     cin>>firstNum;
  12.     cout<<"Enter value for Second Number:  ";
  13.     cin>>secondNum;
  14.     cout<<"\n\n";
  15.     cout<<"Values BEFORE Calling Built in Swap Function"<<endl<<endl;
  16.     cout<<"\tFirst  Number = "<<firstNum<<endl;
  17.     cout<<"\tSecond Number = "<<secondNum<<endl;
  18.      cout<<"\n\n";
  19.  
  20.     std::swap( firstNum , secondNum );
  21.  
  22.     cout<<"Values AFTER Calling Bulit in  Swap Function"<<endl<<endl;
  23.     cout<<"\tFirst Number = "<<firstNum<<endl;
  24.     cout<<"\tSecond Number = "<<secondNum<<endl;
  25.     return 0;
  26. }         

Note: If we remove std:: from swap at line number 20 than built in function will not run but The Function which has written above main will run

If the function above the main is not written and we remove std:: from built in function than built in function will run 


When we call a function in a program compiler look into our code if compiler not found the function body which has called it look into standard library where he found the body it runs it.

Image View OF Code: (click on image for large view)
Built in swap function in c++ example code
swap function example in c++ programming


sample output

1 comment: