In: Computer Science
In Coral. Given a sorted list of integers, output the
middle integer .Assume the number of integers ia odd. Ex: if the
input 2 3 4 8 11 -1(a negative indicates end), the output is
4.
the maximum number of inputs for any test case should not exceed 9
positive values. If exceeded , output Too many inputs". Hint: Use
an array of size 9. First read the data into array.Then,based in
the number of items, find the middle item.
The logic for this is simple. Keep taking input until -1 is given and for every input, increment the count value (0 indexed) so that when the count becomes 8 (actually 9), it means 9 elements are given so any more input causes "Too many inputs" as output. The code is shown below:
// Create an array of size 9
integer array(9) nums
integer x
integer count
// To check if broke while because of overflow count
integer flag
count = 0
// Initialize it to 0
flag = 0
while x != -1
x = Get next input
// If count is 8, required elements are got (9)
// So no need of any more so to break, put x = -1
if count == 9
if x != -1
x = -1
flag = 1
// If x is not -1, put in array and increment count
if x != -1
nums[count] = x
count = count + 1
// If broke while because of count
if flag == 1
Put "Too many inputs" to output
else
Put nums[count/2] to output
A screenshot for indentation purposes which will help you to code clearly is given below:
A screenshot of the output for two different inputs:
and
Hope this is helpful. In case of any queries, please comment below. All the best :)