Header Ads Widget

Program to find the closest value | unthinkable solutions

 Program to find the closest value 

Given an array of integer and a value , write a program to to find the closest value .

Sample input:

12 3 2 23 5
15

Sample output:

12



Program to find the closest value 

The objective of the code is to find the closest value to the given target value . 

Code:-

#include<bits/stdc++.h>
using namespace std;

// function for finding the Closest value
int Findclosetvalue(vector<int>&arr,int target)
{
int dif=INT_MAX;
int ans;
for(int i=0;i<arr.size();i++)
{
if(dif>abs(target-arr[i]))
{
dif=abs(target-arr[i]);
ans=arr[i];
}
}
return ans;
}

// Driver function

int main()
{
vector<int> arr;
int n,target;
cout<<"Enter size of array"<<endl;
cin>>n;
int ele;
cout<<"Enter elements of the array"<<endl;
for(int i=0;i<n;i++)
{
cin>>ele;
arr.push_back(ele);
}
cout<<"Enter the target value"<<endl;
cin>>target;
cout<<"Closest element to the "<<target<<" is "<<Findclosetvalue(arr,target);
return 0;
}

Output:

Enter size of array
5
Enter elements of the array
12 3 2 23 5
Enter the target value
15
Closest element to the 15 is 12

Wipro :-

Infytq :-

Key Points;-

Hackerrank:-


C-tutorial:-

See more:-