108k views
1 vote
Write and test a function that takes the addresses of three double variables as arguments and that moves the value of the smallest variable into the first variable, the middle value to the second variable, and the largest value into the third value.

User Tyronen
by
8.5k points

1 Answer

3 votes

Answer:

#include <bits/stdc++.h>

using namespace std;

// function to swap largest to third, smallest to first and middle to second

void valueSwap(double *a,double *b,double *c)

{

// variables

double f,s,t;

// if value of first is greater than second

if(*a>=*b)

{

// if value of first is greater than third

if(*a>=*c)

{

// swap

t = *a;

if(*c>=*b)

{

s = *c;

f = *b;

}

else

{

//swap

f = *c;

s = *b;

}

}

else

{

//after all the swap

f = *b;

s = *a;

t = *c;

}

}

else

{

// if value of second is greater than third

if(*b>=*c)

{

t = *b;

if(*c>=*a)

{

// swap

s = *c;

f = *a;

}

else

{

//swap

f = *c;

s = *a;

}

}

else

{

// after all the swap

t = *c;

s = *b;

f = *a;

}

}

// final values

*a = f;

*b = s;

*c = t;

}

// main function

int main()

{

// variables

double n1,n2,n3;

// ask to enter first number

cout<<"Enter the first number:";

// read first number

cin>>n1;

// ask to enter second number

cout<<"Enter the second number:";

// read second number

cin>>n2;

// ask to enter third number

cout<<"Enter the third number:";

// read third number

cin>>n3;

// call the function to swap values with address parameter

valueSwap(&n1,&n2,&n3);

// print number after swapping

cout<<"Number after swapping: "<<n1<<" "<<n2<<" "<<n3<<endl;

return 0;

}

Step-by-step explanation:

Ask user to enter 3 double numbers.Then read 3 numbers from user and assign them to variables "n1","n2" and "n3" respectively.Call the function valueSwap() which take address of all three variables as argument and then assign the largest value among the three to variable "n3" and smallest to "n1" and middle to variable "n2". Print the values after swapping.

Output:

Enter the first number:20

Enter the second number:30

Enter the third number:10

Number after swapping: 10 20 30

User Sergio Del Amo
by
8.2k points