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
swap
function is defined that takes two integer parametersnum1
andnum2
by reference. The function swaps the values ofnum1
andnum2
using a temporary variabletemp
.The
main
function is defined, which declares two integer variablesnum1
andnum2
to store the user inputs.The
cout
statement is used to prompt the user to enter the value ofnum1
.The
cin
statement is used to read the value ofnum1
entered by the user from the console.The
cout
statement is used to prompt the user to enter the value ofnum2
.The
cin
statement is used to read the value ofnum2
entered by the user from the console.The values of
num1
andnum2
before the swap operation are printed on the console using thecout
statement.The
swap
function is called with the input values ofnum1
andnum2
to swap their values.After the swap operation, the values of num1 and num2 are printed on the console using the
cout
statement.The
return 0
statement 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