Thursday, July 30, 2009

Function calling array C++?

Hi, I'm stuck on a problem I'm doing, I was wondering if someone could help. I need to create 3 functions


1. Max temp


2. Min temp


3. Average temp





An array will be populated with the appropriate no of temps . The functions will perform the calculations and display the results to the user





How would I approach this? I'm only started to learn about arrays and am clueless really. How would I find the max and min in a function?





I would really appreciate any help you culd provide

Function calling array C++?
int fn_GetMax(int* pInput, int length)


{


int ret = -1 ;


if(pInput != 0 %26amp;%26amp; length %26gt;= 1)


{


ret = pInput[0];





for(int i=1; i%26lt;length; i++)


if(pInput[i]%26gt; ret) ret = pInput[i] ;





}





return ret;


}





int fn_GetMin(int* pInput, int length)


{


int ret = -1 ;


if(pInput != 0 %26amp;%26amp; length %26gt;= 1)


{


ret = pInput[0];





for(int i=1; i%26lt;length; i++)


if(pInput[i]%26lt; ret) ret = pInput[i] ;





}





return ret;


}





int fn_GetAvr(int* pInput, int length)


{


if(pInput == 0 || length %26lt;= 0)


return 0;


int sum = 0 ;


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


sum+= pInput[i];





return sum/length;


}





______________________________________...





good luck
Reply:Well, with out giving it completely away in code:





Draw it out on a sheet of paper, use an array with 5 elements as an example. Make up some temps {32,-4,78,55,77}.





Now, imagine you can't see the array, except for the first element. How would you go through the entire array and determine the maximum temp (the highest number) or the minimum temp (lowest number)?





Basically, you want to compare each number until you find the largest or smallest. Just start with the first element: for maximum: if the first number (current) is smaller than the next, then next becomes the current and compare it to the next number. If the next number is smaller than current, then keep the current number as current. For smaller, reverse the logic.





Average, well, you know what that is, add it all up and divide by the number of elements.
Reply:For the minimum and maximum, "guess" a minimum and maximum as some element of the array. Then, loop through the array, and if you find anything greater than your current guess for the maximum or anything smaller than your current guess for the minimum, then update your guess appropriately. When you are done, the guess for the minimum/maximum will be the actual minimum and maximum values. For the mean, simply sum all the elements and then divide by the number of elements, the same as you would by hand.


No comments:

Post a Comment