Monday, May 24, 2010

C++ help please!!?

This is not my homework..I have to know how to do this inorder to do my project next week..Just trying to get a head start!!





Write a function


void sort3(int%26amp; a, int%26amp; b, int%26amp; c) {


}


that sorts three numbers in ascending order. For example,





int a=8;


int b=10;


int c=4;


sort3(a,b,c);


printf(‘‘small: \%d, middle: \%d, large: \%d\n’’,a,b,c);


should have output:


smallest: 4, middle: 8, largest: 10

C++ help please!!?
Assume you want the "sort" function to do the sorting and not just print the info. This routine will perform a simple sort and can be expanded very easily.





void sort(int a, int b, int c) {





int mynums[3], x, y, tmp;


mynums[0]=a;


mynums[1]=b;


mynums[2]=c;





for (x=0; x%26lt;2; x++) {


for (y=x+1; y%26lt;3; y++) {


if (mynums[x] %26gt; mynums[y]) {


tmp=mynums[x];


mynums[x]=mynums[y];


mynums[y]=tmp;


}


}


}


a=mynums[0];


b=mynums[1];


c=mynums[2];


}
Reply:I don't know if this is what your instructor had in mind (probably he wanted you to implement the sorting yourself). But I will post my solution anyway. It uses the STL sort algorithm.





#include %26lt;algorithm%26gt;


using namespace std;





void sort3(int %26amp;a, int %26amp;b, int %26amp;c) {


int num[3];





num[0] = a;


num[1] = b;


num[2] = c;





sort(%26amp;num[0], %26amp;num[3]);





a = num[0];


b = num[1];


c = num[2];


}





int main() {


int a = 4, b = 10, c = 6;





sort3(a, b, c);


}
Reply:void sort3(int a, int b, int c)


{





IF (a %26lt; b) THEN


IF (a %26lt; c) THEN


IF (b %26lt; c) THEN


printf( a, b, c)


ELSE


printf( a, c, b)


END IF


ELSE


printf(c, a, b)


END IF


ELSE


IF (b %26lt; c) THEN


IF (a %26lt; c) THEN


printf( b, a, c)


ELSE


printf( b, c, a)


END IF


ELSE


printf(c, b, a)


END IF


END IF





}


int a=8;


int b=10;


int c=4;


sort3(a,b,c);








hope this will solve your problem, if you still have any problem you can reach me at asim_developer@yahoo.com


or i will be online at asimhero2003@yahoo.com





Thanks


Asim

cvs

No comments:

Post a Comment