|
|
|
Max & Min Values in Arrays (C)
|
Original Message
|
Name: paul.browne03
Date: November 18, 2003 at 10:43:11 Pacific
Subject: Max & Min Values in Arrays (C) OS: Win ME CPU/Ram: 2.4GHz/512MB
|
Comment: As part of the program I'm currently in the process of writing it's become necessary to be able to search an array, which has a maximum size of twenty elements, & extract the max, the min & the mean average values from this array. I've been using FOR loops to try this, correctly or incorrectly I don't know. The code currently looks like this; min = temp[0]; max = temp[0]; for (j = 0; j < i; j++) { if (temp[j] < min) { min = temp[j]; } } for (k = 0; k < i; k++); { if (temp[k] > max) { max = temp[k]; } } That's only the code for the max & min, I haven't begun ruminating on the average yet. My difficulty is this; the min loop runs perfectly. however the max loop only serves to find the min value somehow. I cannot see how it's failing at all, at all. Does anyone have any ideas?
Report Offensive Message For Removal
|
|
Response Number 1
|
Name: Daemon Rose
Date: November 18, 2003 at 11:28:27 Pacific
|
Reply: (edit)You have a ; after your second for loop...take it out and it should run fine ie: for (k = 0; k < i; k++) { if (temp[k] > max) { max = temp[k]; } }
Report Offensive Follow Up For Removal
|
|
Response Number 2
|
Name: paul.browne03
Date: November 18, 2003 at 11:56:05 Pacific
|
Reply: (edit)Bugger, I can't believe I missed something that simple! I pored over it for an hour too!. Just goes to show how simple a problem can really be, I suppose. Thanks a lot, Daemon Rose, it probably would have taken me ages to find that one, tiny ; otherwise.
Report Offensive Follow Up For Removal
|
|
Response Number 4
|
Name: DEEP_FX
Date: November 21, 2003 at 23:37:40 Pacific
|
Reply: (edit)That is the way to do it. It would also become more efficient if you were to start the loop at 1 instead of 0, as you have already initialized the min and max values to the array at 0. :). You would, however, start computing the average value of an array at zero. consider the following fragment. double average = 0; int i; for (i = 0; i < 20; i++) average += temp[i]; average /= i; keep in mind that i actualy is twenty when we divide average by it. We know this because it must become twenty for the loop to be exited.
Report Offensive Follow Up For Removal
|
Use following form to reply to current message:
|
|

|