Program:
#include <iostream>
using namespace std;
void swap(int &num1, int &num2){
int temp;
temp = num1;
num1 = num2;
num2 = temp;
}
int main(){
int num1, num2;
cout<<"Enter the value of num 1: ";
cin>>num1;
cout<<"Enter the value of num 2: ";
cin>>num2;
cout<<"Before Swap: "<<endl;
cout<<"num1 = "<<num1<<endl;
cout<<"num2 = "<<num2<<endl;
swap(num1, num2);
cout<<"After Swap: "<<endl;
cout<<"num1 = "<<num1<<endl;
cout<<"num2 = "<<num2<<endl;
return 0;
}
Output:
The program starts by including the iostream library, which provides basic input and output functionalities in C++.
A
swapfunction is defined that takes two integer parametersnum1andnum2by reference. The function swaps the values ofnum1andnum2using a temporary variabletemp.The
mainfunction is defined, which declares two integer variablesnum1andnum2to store the user inputs.The
coutstatement is used to prompt the user to enter the value ofnum1.The
cinstatement is used to read the value ofnum1entered by the user from the console.The
coutstatement is used to prompt the user to enter the value ofnum2.The
cinstatement is used to read the value ofnum2entered by the user from the console.The values of
num1andnum2before the swap operation are printed on the console using thecoutstatement.The
swapfunction is called with the input values ofnum1andnum2to swap their values.After the swap operation, the values of num1 and num2 are printed on the console using the
coutstatement.The
return 0statement is used to terminate the program.
Overall, this is a simple program that demonstrates the use of functions and passing parameters by reference in C++.
No comments:
Post a Comment