Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Use functional decomposition to write a C++ program that determines the median o

ID: 3595997 • Letter: U

Question

Use functional decomposition to write a C++ program that determines the median of

three input numbers. The median is the middle number when the three numbers are

arranged in order by size. However, t

he user can input the values in any order, so

your program must determine which value is between the other two. For example, if

the user enters

41.52 27.18 96.03

Then the program would output

The median of 41.52, 27.18, and 96.03 is 41.52.

Once you have the three

-

number case working, extend the program to handle five

numbers. Be sure to use proper formatting and appropriate comments in your code.

The output should be labeled clearly and formatted neatly.

Explanation / Answer

For just three numbers this is the solution -

#include<iostream>

using namespace std;
int main()
{
float a , b , c ;
float median ;
cout<<"Enter three numbers ";
cin >> a >> b>> c ;
if ((b>a&&b<c)||(b<a&&b>c))
{
median = b ;
}
else
if((a>b&&a<c)||(a<b&&a>c))
{
median = a ;
}
else
if((c<a&&c>b)||(c>a&&c<b))
{
median = c;
}
else if(a==b)
{
median = a ;
}
else
{
median=c;
}
cout << "Median is "<<median << endl ;

return 0;
}

But with incrasing range of inputs writing programs in this way is really difficult .

So to get median for a larger range sort the range and get middle one element.

if even number of elements are there , the median is the average of n/2 th element and ((n/2)+1)th element and odd number of elements are there then median is (n+1)/2 th element.

so here is the program -

#include<iostream>

using namespace std;
int main()
{
float a[10] , t ;
float median ;
int n , i , j ;
cout<<"Enter range of numbers ";
cin >> n ;
cout <<"Enter the numbers to find median ";
for(i=0;i<n;i++)//reading elements
{
cin >> a[i];
}
//to sort the entered values in ascending order
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
  
}
}
}
if(n%2==1)//when range of the elements is odd
{
median=a[(n+1)/2];
}
else//when range of the elements is even
{
median = (a[(n/2)-1]+a[(n/2)])/2;
}
cout << "Median is "<<median << endl ;

return 0;
}