Lets say people say

1,3,4,6,9,10,44

And the correct answer is 5. How do I calculate the closest number to 5? Thanks.

loop through the array and subtract '5' from each element.
Use abs() on the outcome.
The smallest outcome is closest to 5

The correct answer is a variable....

It can be changed to 5, 10, 100000000000....depends.

Doesn't matter. Just subtract any number you want to compare with from each element in the array and follow my advice in my previous post.

Drawing these things out on paper makes you understand them better.

Thats the simplest method as stated niek_e
And after that it all depends that on tricks you apply to solve.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.