You are here:

C++/C assending integers alghorithm

Advertisement


Question
QUESTION: 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

Answer
void 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
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.