Yizhi Hu
Yizhi Hu

Reputation: 57

sorting three number in a specific order

So, I am just trying to sort three numbers in a specific order indicated by user. Example

So, in this example, user input three numbers: 1 5 3, and wanna sort them in ABC order which means from minimal to middle to maximum. So, it output 1 3 5. Second example is sorting in CAB order, which means maximal to minimal to middle.

#include <stdio.h>
#include<stdlib.h>

int main()
{
   int i,array[3];
   for(i = 0; i < 3; i++)
    scanf("%d",&array[i]);
   int max,mid,min;
   max = array[0];
   mid = array[0];
   min = array[0];
   for(i = 0; i < 3; i++){
       if(max < array[i])
       max= array[i];
       if(min > array[i])
            min = array[i];
   }
   for(i = 0; i < 3; i++){
       if(array[i] != max || array[i]!= min)
         mid = array[i];
  }
   char A,B,C;
   scanf("%c%c%c",&A,&B,&C);

   if(A == 'A')
    printf("%d ",min);

   if(B == 'A')
     printf("%d ",min);
    if(C == 'A')
        printf("%d ",min);
    if(A =='B')
        printf("%d ",mid);
    if(B == 'B')
        printf("%d ",mid);
    if(C =='B')
        printf("%d ",mid);
    if(A == 'C')
        printf("%d ",max);
    if(B == 'C')
        printf("%d ",max);
    if(C == 'C')
        printf("%d ",max);


}

Basically, I am just find the max, min and mid in three numbers. Then test the letter A,B or C.

If I input 1 5 3 and ABC(first example), it would print out only 1 3. For the second example, it only prints out 6 2.

What causes this bug and is there any better way to do this algorithm?

Upvotes: 2

Views: 487

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140196

First, the mid calculation is wrong (logic error), should be:

for(i = 0; i < 3; i++){
    if(array[i] != max && array[i]!= min) // AND not OR
     {
      mid = array[i];
      break; // once found you can break
    }

then it's the infamous "scanf eats last linefeed bug", which puts \n in A because you previously entered the list of the numbers, and shifts the rest of your variables too. You can fix it like this:

scanf(" %c%c%c",&A,&B,&C);

Upvotes: 3

Related Questions