Write a program that reads three integer values (A, B and C) on the keyboard. Sort the values A, B and C by successive exchanges so as to obtain: val (A) $$\leq$$ val (B) $$\leq$$ val (C).


Difficulty level
Video recording
This exercise is mostly suitable for students
Solution 1
#include <stdio.h>

int main()
{
    int A , B , C;
    int aux;
    
    printf("Enter 3 integers: ");
    scanf("%d %d %d", &A, &B, &C);
    
    printf("Before sorting: \n \tA=%d\n\tB=%d\n\tC=%d\n", A, B ,C);

    if(A>B)
    {
        aux=A;
        A=B;
        B=aux;
    }

    if(C<A)
    {
        aux=C;
        C=A;
        A=aux;
    }
   
     if(C<B)
     {
         aux = B;
         B=C;
         C=aux;
    }
    
    printf("After sorting: \n \tA=%d\n\tB=%d\n\tC=%d\n", A, B ,C);

    return 0;
}



Solution 2
#include <stdio.h>

int main()
{
    int A , B , C;
    int aux;
    
    printf("Enter 3 integers: ");
    scanf("%d %d %d", &A, &B, &C);
    
    printf("Before sorting: \n \tA=%d\n\tB=%d\n\tC=%d\n", A, B ,C);

    if(A>B)
    {
        aux=A;
        A=B;
        B=aux;
    }
    

    if(C<A)
    {
        aux=C;
        C=B;
        B=A;
        A=aux;
    }
    else
        if(C<B)
        {
            aux = B;
            B=C;
            C=aux;
        }
    
    printf("After sorting: \n \tA=%d\n\tB=%d\n\tC=%d\n", A, B ,C);

    return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Balanced binary trees