top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+2 votes
736 views
Find two closest number in a given array using C/C++?
posted Jan 20, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

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;

}
answer Jan 21, 2016 by Shivaranjini
Similar Questions
0 votes

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

0 votes

Given an unsorted array which has a number in the majority (a number appears more than 50% in the array), how to find that number?

+2 votes

Say you are given an array which has all duplicate members except one, which out this non-duplicate member.

...