Write a C++ function, indexSmallest(), that takes a two-dimensional array on integers with 10
rows and 1 0 columns. Along with the array, other arguments are two integers. The function will search
the array of its smallest element. The two integers will represent the indices (row and column) of the
smallest element. Also, write a program to test your function.
Sample Run:
1)
The smallest element is 1.
It is located on row 9 and column 8.
2)
The smallest element is 2.
It is located on row 5 and column 4.
3)
The smallest element is 5.
It is located on row 5 and column 0.
#include <iostream>
using namespace std;
int indexSmollest(int arr[10][10], int& row, int& col) {
row = col = 0;
int minEl = arr[row][col];
for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
if (arr[i][j] < minEl) {
row = i;
col = j;
minEl = arr[row][col];
}
}
}
return minEl;
}
int main(int argc, char *argv[])
{
int arr1[10][10] = { {11, 12, 13, 14, 15, 16, 17, 18, 19, 10},
{21, 22, 23, 24, 25, 26, 27, 28, 29, 20},
{31, 32, 33, 34, 35, 36, 37, 38, 39, 30},
{41, 42, 43, 44, 45, 46, 47, 48, 49, 40},
{51, 52, 53, 54, 55, 56, 57, 58, 59, 50},
{61, 62, 63, 64, 65, 66, 67, 68, 69, 60},
{71, 72, 73, 74, 75, 76, 77, 78, 79, 70},
{81, 82, 83, 84, 85, 86, 87, 88, 89, 80},
{91, 92, 93, 94, 95, 96, 97, 98, 99, 90},
{11, 12, 13, 14, 15, 16, 17, 18, 1, 10} };
int arr2[10][10] = { {11, 12, 13, 14, 15, 16, 17, 18, 19, 10},
{21, 22, 23, 24, 25, 26, 27, 28, 29, 20},
{31, 32, 33, 34, 35, 36, 37, 38, 39, 30},
{41, 42, 43, 44, 45, 46, 47, 48, 49, 40},
{51, 52, 53, 54, 55, 56, 57, 58, 59, 50},
{61, 62, 63, 64, 2, 66, 67, 68, 69, 60},
{71, 72, 73, 74, 75, 76, 77, 78, 79, 70},
{81, 82, 83, 84, 85, 86, 87, 88, 89, 80},
{91, 92, 93, 94, 95, 96, 97, 98, 99, 90},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 10} };
int arr3[10][10] = { {11, 12, 13, 14, 15, 16, 17, 18, 19, 10},
{21, 22, 23, 24, 25, 26, 27, 28, 29, 20},
{31, 32, 33, 34, 35, 36, 37, 38, 39, 30},
{41, 42, 43, 44, 45, 46, 47, 48, 49, 40},
{51, 52, 53, 54, 55, 56, 57, 58, 59, 50},
{ 3, 62, 63, 64, 65, 66, 67, 68, 69, 60},
{71, 72, 73, 74, 75, 76, 77, 78, 79, 70},
{81, 82, 83, 84, 85, 86, 87, 88, 89, 80},
{91, 92, 93, 94, 95, 96, 97, 98, 99, 90},
{11, 12, 13, 14, 15, 16, 17, 18, 19, 10} };
int row, col;
int minEl;
cout << "Test 1" << endl;
minEl = indexSmollest(arr1, row, col);
cout << "The smallest element is " << minEl << endl;
cout << "It is located on row " << row << " and column " << col << endl << endl;
cout << "Test 2" << endl;
minEl = indexSmollest(arr2, row, col);
cout << "The smallest element is " << minEl << endl;
cout << "It is located on row " << row << " and column " << col << endl << endl;
cout << "Test 3" << endl;
minEl = indexSmollest(arr3, row, col);
cout << "The smallest element is " << minEl << endl;
cout << "It is located on row " << row << " and column " << col << endl << endl;
return 0;
}
Comments
Leave a comment