Tuesday, July 28, 2009

Please help!write a C++ program that finds the position of the smallest and largest number in an array double?

Go through the array. Have two variables.


double smallest = MAX_DOUBLE_VALUE; //Get this from the limits.h include file. I'm not sure if that's the exact way to do it, but that's it.


double largest = MIN_DOUBLE_VALUE; //Same as for MAX.





The reason you do the min and the max for the opposite variables is that you are guaranteed to change them then, no matter the number range.





int lcv = 0;


int position_smallest;


int position_largest;





int array_length = sizeof(array) / sizeof(array[0];





for( ; lcv %26lt; array_length; lcv++)


{


if(array[lcv] %26lt; smallest)


{


smallest = array[lcv];


position_smallest = lcv;


}


if(array[lcv] %26gt; largest)


{


largest = array[lcv];


position_largest = lcv;


}


}





There you go, now your two variables position_smallest and position_largest have the positions of the numbers you are looking for.





Hope it helps! If you have any more questions about the code, I'd be more than happy to help.

Please help!write a C++ program that finds the position of the smallest and largest number in an array double?
#include %26lt;iostream%26gt;


using namespace std;








void slposition (double b[], int size)


{


int i;


double small=b[0];


double big=b[0];


int smallindex=0;


int bigindex=0;


for(i=1;i%26lt;size;i++){


if (small %26gt; min(small,b[i])) smallindex=i;


if (big %26lt; max(big,b[i])) bigindex=i;


}


cout %26lt;%26lt; "\n position of the smallest : " %26lt;%26lt; smallindex;


cout %26lt;%26lt; "\n position of the largest : " %26lt;%26lt; bigindex;


return;


}





main () {


double a[10];


int n,i;





while(true){





system("cls");


cout %26lt;%26lt; "\nEnter number of the elements :";


cin %26gt;%26gt; n;


for(i=0;i%26lt;n;i++){


cout %26lt;%26lt; "\nEnter element " %26lt;%26lt; i %26lt;%26lt; " : ";


cin %26gt;%26gt; a[i];


}


slposition (a,n);


cout %26lt;%26lt; endl %26lt;%26lt; endl;


system("pause");


}


}
Reply:http://answers.yahoo.com/question/index;...
Reply:With c++ you have the luxury of STL. Just use the sort algorithm and use the iterators calls begin() and end() to get the smallest and largest values.


No comments:

Post a Comment