Friday, July 31, 2009

DEV-C++(How to create a 2d-array)?

I need to create a 2 dimension array .whats the code to create a 5 rows and 10 columns vector of any numbers then finding the maximum ,minimum and average value.I am using DEV - C++.Help please!

DEV-C++(How to create a 2d-array)?
I hope you have a rough idea of what you're doing, cause I'm going to just psuedocode this really quick. Without you giving me a head start, it will take me forever. Question though, are you making an array? or a vector? they're different you know, vectors dont need to be a set size initially for example. Below is an array.





int row = 4;


int column = 9;


int number; //inputted number


int min=0; //for comparing for min


int max = 0; //comparing for max


int avg;


int array[row][column]; //here is your array - i might have gotten them switched





for(int i=0; i%26lt;5; i++) //loop to go thru row


{


for(int j = 0; j%26lt;10; j++) //nested loop to go thru column


cin %26lt;%26lt; number;


}





for (i=0; i %26lt; 5; i++) //loop again for finding max min avg


{


for (int j=0; j%26lt;10; j++)


{if number %26gt; max


max = number


//compute stuff for min, and average here


}


}





ok lost my train of thought, you can do the rest.... =)
Reply:double[5][10] vector; //definition





for(int i=0; i%26lt;5; i++)


for(int j=0; j%26lt;10; j++)


cin%26gt;%26gt;vector[i][j]; //reads element from row i and column j





double maximum = vector[0][0];


posR = 0;


posC = 0;





for(int i=0; i%26lt;5, i++)


for(int j=0; j%26lt;10; j++)


if (maximum%26lt;vector[i][j])


{


maximum = vector[i][j];


pozR = i;


pozC = j;


}





maximum - the value of the max element.


pozR+1 - the row maximum is found on


pozC+1 - the column maximum is found on





If more than one element has the value of maximum, the first occurrence is taken into account.





minimum goes the same way, the only difference is that you check whether minimum%26gt;vector[i][j].





sum = 0;


for(int i=0; i%26lt;5; i++)


for(int j=0; j%26lt;10; j++)


sum+=vector[i][j];





double average = sum/50;





The total number of element is 5*10 = 50 (no of rows multiplied by no of columns).





P.S. you can calculate all 3: max, min and avg during one single parsing of the vector. Lessens time.


No comments:

Post a Comment