# Find two closest number in a given array using C/C++?

327 views
Find two closest number in a given array using C/C++?
posted Jan 20, 2016

finds the second largest number within an array.

``````#include <iostream>

#include <cmath>

using namespace std;

const int MAXX = 5;

int findKey(int[], int);

//function main

int main(){

int RandNumbs[MAXX] = { 4, 8, 12, 16, 20};

int SearchKey;

int NearestNum;

cout << "Enter number to search: ";

cin >> SearchKey;

NearestNum = findKey(RandNumbs, SearchKey);

cout << "The closest number to the entered number in the "

<< "array is " << RandNumbs[NearestNum] << endl;

return 0;

}

int findKey(int Array1[], int key){

int diff = abs( key - Array1[0]);

int Num1 = 0;

int Num2 = 0;

for (int a = 0; a < MAXX; a++)

{

if (diff > abs( key - Array1[a] ))

{

diff = abs( key - Array1[a]);

Num1 = Array1[a];

}

}

return Num1;

}
``````
Similar Questions

Given an array of sorted integers and find the closest value to the given number. Array may contain duplicate values and negative numbers.

Example : Array : 2,5,6,7,8,8,9
Target number : 5
Output : 5

Target number : 11
Output : 9

Target Number : 4
Output : 5