C++/C assending integers alghorithm
Expert: vijayan - 11/13/2008
QuestionQUESTION: Hi
I have a mid-term coming up on C. One of the practice problems was to ask the user for 3 integers and then print out the sorted result in ascending order. I have a quick question regarding my algorithm and I may need some programming help too.
I started out getting 3 integers from the user with scanf statements and assigning them to variables i, j and k. My initial plan was to just use if statements and check which integer was bigger than the other, but that would be really repetitive. Is there is an easier way to do this. (easier alghotihm to arrange integers in alphabetical order)
Thank You
Raheel
ANSWER: from the question, i presume that you have not yet come to arrays or functions. if that is the case, you have to rely on if statements.
you could reduce them to three by swapping the values appropriately to get them arranged in alphabetical order.
int main()
{
int i, j, k ;
// get i, j, k from user
if( i > j )
{
int temp = i ;
i = j ;
j = temp ;
}
if( j > k )
{
int temp = j ;
j = k ;
k = temp ;
}
if( i > j )
{
int temp = i ;
i = j ;
j = temp ;
}
// print i, j, k
return 0 ;
}
if you are familiar with functions and pointers, you could write a swap function to take care of the repetitive part of the code.
or if you understand preprocessor macros, you could write a swap macro.
---------- FOLLOW-UP ----------
QUESTION: Thank you for your reply. How would I do this using arrays or pointers. Thank You
Answervoid swap( int* a, int* b )
{
int temp = *a ;
*a = *b ;
*b = temp ;
}
int main()
{
int i, j, k ;
// get i, j, k from user
if( i > j ) swap( &i, &j ) ;
if( j > k ) swap( &j, &k ) ;
if( i > j ) swap( &i, &j ) ;
// print i, j, k
}