In: Computer Science
Suppose you have a list containing k integer numbers. Each number could be positive, negative, or zero. Write pseudocode for a program that first asks the user for each of the numbers. After that, it should determine and display the number from the list that is nearest to the positive number five (5).
Notes:
1. Try working this out for k = 4 and k = 5. See if you can find an
algorithmic pattern that can be extended for any value of k.
2. For those of you who have prior programming experience, think
about how you might simulate this process using arrays.
Thanks for the question, Here is the algorthm using Arrays
====================================================================
DECLARE numbers[3] as INTEGER
num <- GET 'First number: "
numbers[0] <- num
num <- GET 'Second number: "
numbers[1] <- num
num <- GET 'Third number: "
numbers[2] <- num
closest_num = numbers[0]
for i = 0 to 2:
if
ABSOLUTE_VALUE(5-numbers[i])<ABSOLUTE_VALUE(5-closest_num)
closest_num = numbers[i]
i <- i + 1
OUTPUT closest_num
====================================================================
Code in C Language
#include<iostream>
#include<math.h>
using namespace std;
int main(){
int numbers[3];
int compare_to = 5;
printf("Enter first number: "); scanf("%d",
&numbers[0]);
printf("Enter second number: "); scanf("%d",
&numbers[1]);
printf("Enter third number: "); scanf("%d",
&numbers[2]);
int closet_number = numbers[0];
int i;
for(i=0; i<3; i++){
if(abs(closet_number-compare_to)>abs(numbers[i]-compare_to))
closet_number =
numbers[i];
}
printf("The nearest number to %d is %d", compare_to,
closet_number);
return 0;
}
===================================================================