C++ Examples

C++ program to swap two numbers using call by value.

#include <iostream>
using namespace std;

void swap(int, int);

int main()
{
    int num1,num2;
    cout<<"Enter the first number ";
    cin>>num1;
    cout<<"Enter the second number ";
    cin>>num2;
    
    cout<<"The numbers before swaping are "<<num1<<" "<<num2<<endl;
    
    swap(num1,num2);
    
    return 0;
}

void swap(int num1, int num2)
{
    int temp;
    
    temp =  num1;
    num1    =  num2;
    num2    =  temp;
    
    cout<<"The numbers after swapping are "<<num1<<" "<<num2<<endl;
}

Output

Enter the first number 45
Enter the second number 63
The numbers before swaping are 45 63
The numbers after swapping are 63 45
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments