124k views
5 votes
Write a C++ program to exchange values of two variables using function exchange().

User Surbina
by
6.8k points

1 Answer

1 vote

Answer:

#include<iostream>

using namespace std;

//create the exchange function

void exchange(int a, int b){

int temp; //initialize temporary

//swap the variables value

temp=a;

a=b;

b=temp;

//print the output after exchange

cout<<"a is: "<<a<<endl;

cout<<"b is: "<<b<<endl;

}

//main function program start from here

int main(){

//initialization

int a=3, b=6;

exchange(a,b); //calling the function

return 0;

}

Step-by-step explanation:

Create the function exchange with two integer parameter which takes the value from the calling function.

and then declare the third variable temp with is used for swapping the value between two variables.

first store the value of 'a' in the temp and then assign the 'b' value to 'a' and then, assign the temp value to b.

for example;

a=2, b=9

temp=2;

a=9;

b=2;

So, the values are swap.

and then print the swap values.

Create the main function and define the input a and b with values.

Then, calling the exchange function with two arguments.

User Turvy
by
6.5k points