/*
Write a function that finds the element closest in value from 2-d array to the number entered by user. The row and column indices of the element closest in value to the element should be the output.
*/
Code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void closest_number_finder(int [][5], int);
int main()
{
cout << "Array:" << endl << endl;
int array[5][5];
for (int r = 0; r<5; r++)
{
for (int c = 0; c<5; c++)
{
array[r][c] = rand()%101 - 50; //Storing random numbers from -50 to 50.
cout << char(179) << setw(3) << array[r][c] << setw(3) << char(179);
}
cout << endl;
}
cout << "\nEnter a Number, I'll tell nearest of this number from my array: ";
int user;
cin >> user;
closest_number_finder(array, user);
return 0;
}
void closest_number_finder(int array[][5], int user)
{
int difference[5][5];
for (int r = 0; r<5; r++)
{
for (int c = 0; c<5; c++)
{
difference[r][c] = fabs(array[r][c] - user);
}
}
int R, C;
//Now we've to find the smallest difference.
int smallest = difference[0][0];
for (r = 0; r<5; r++)
{
for (int c = 0; c<5; c++)
{
if (smallest > difference[r][c])
{
smallest = difference[r][c];
R = r; C = c;
}
}
}
cout << "Closest to your entered number is " << array[R][C] << " at table[" << R << "][" << C << "]" << " with a difference of " << smallest << endl;
}
No comments:
Post a Comment