Hey guys,
My lecturer told me that when I have solved a problem, I should always look for ways to improve it.
I was wondering if it is okay to post my code here and ask the community to comment and tell me if it can be improved, but I don't want to be told how. Hints are welcome though.
Problem: Find the minimum and maximum of each column and row of a 2D array.
I have spent about 1 hour so far and it works. This problem did confuse me with all the min's and max's.
I was thinking it could be done in one set of for loops, but I'm not sure.
Heres my code:
#include <iostream>
#include <ctime>
using namespace std;
struct MinMax
{
int min;
int max;
};
void initializeArray(int randomArray[][5]);
void determineRowMinMax(int randomArray[][5], MinMax rowMinMax[]);
void determineColMinMax(int randomArray[][5], MinMax colMinMax[]);
void displayArray(int randomArray[][5]);
void displayMinMax(MinMax rowMinMax[], MinMax colMinMax[]);
void main()
{
//No constant declarations
//Variable declartions
int randomArray[5][5];
MinMax rowMinMax[5];
MinMax colMinMax[5];
//Executable statements
initializeArray(randomArray);
determineRowMinMax(randomArray, rowMinMax);
determineColMinMax(randomArray, colMinMax);
displayArray(randomArray);
displayMinMax(rowMinMax, colMinMax);
}
void initializeArray(int randomArray[][5])
{
srand(unsigned(time(0)));
for(int row = 0; row < 5; row++)
{
for(int col = 0; col < 5; col++)
{
randomArray[row][col] = (rand() % 9) + 1;
}
}
}
void determineRowMinMax(int randomArray[][5], MinMax rowMinMax[])
{
for(int row = 0; row < 5; row++)
{
rowMinMax[row].min = randomArray[row][0];
rowMinMax[row].max = randomArray[row][0];
for(int col = 0; col < 5; col++)
{
if(randomArray[row][col] < rowMinMax[row].min)
{
rowMinMax[row].min = randomArray[row][col];
}
if(randomArray[row][col] > rowMinMax[row].max)
{
rowMinMax[row].max = randomArray[row][col];
}
}
}
}
void determineColMinMax(int randomArray[][5], MinMax colMinMax[])
{
for(int col = 0; col < 5; col++)
{
colMinMax[col].min = randomArray[0][col];
colMinMax[col].max = randomArray[0][col];
for(int row = 0; row < 5; row++)
{
if(randomArray[row][col] < colMinMax[col].min)
{
colMinMax[col].min = randomArray[row][col];
}
if(randomArray[row][col] > colMinMax[col].max)
{
colMinMax[col].max = randomArray[row][col];
}
}
}
}
void displayArray(int randomArray[][5])
{
for(int row = 0; row < 5; row++)
{
for(int col = 0; col < 5; col++)
{
cout << randomArray[row][col] << " ";
}
cout << endl;
}
}
void displayMinMax(MinMax rowMinMax[], MinMax colMinMax[])
{
cout << "\n Min Max" << endl;
for(int i = 0; i < 5; i++)
{
cout << "R" << i + 1 << ": " << rowMinMax[i].min << " " << rowMinMax[i].max << endl;
}
for(int i = 0; i < 5; i++)
{
cout << "C" << i + 1 << ": " << colMinMax[i].min << " " << colMinMax[i].max << endl;
}
}