In: Computer Science
You need to write a program that reads in two integers from cin and outputs an horribly inefficent calculation of the median value.
First count from the first number to the second, but stop one short.
Then, count from that number back towards the first, again stopping one short.
Continue until you reach a single number.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Note: Remove all cout statements inside while loop, if you do not want to display the calculation process. Those are used to demonstrate the working of the program using given algorithm.
#include<iostream>
using namespace std;
int main(){
int lower, upper;
//asking and reading values for lower and upper bounds
cout<<"Enter lower and upper numbers to calculate the median: ";
cin>>lower>>upper;
//looping as long as lower is less than upper, assuming user enter valid values
//note: remove all cout statements inside while loop if you do not want to see the
//calculation process
while(lower<upper){
//looping from lower to upper -1
for(int i=lower;i<=upper-1;i++){
//displaying i
cout<<i;
}
cout<<endl;
//advancing lower by one position forward
lower++;
//now looping in reverse, from upper-1 to lower
for(int i=upper-1;i>=lower;i--){
cout<<i;
}
cout<<endl;
//advancing upper by one position backward
upper--;
}
//finally displaying the current lower bound as the median value.
//note: if there are even number of values between the user entered
//range, then median will contain decimal values, but here we deal
//with integers only, so the median will be an integer rounded to
//next integer, for example, if the median is 8.5, the program will
//display 9
cout<<"Median is "<<lower<<endl;
return 0;
}
/*OUTPUT*/
Enter lower and upper numbers to calculate the median: 1 9
12345678
8765432
234567
76543
3456
654
45
5
Median is 5