kanpeki
kanpeki

Reputation: 445

Arranging 3 numbers in ascending order - function not working as expected

As part of a bigger problem I have to sort 3 numbers in ascending order. A simple enough task, but for some reason I'm not getting the expected result. Using arrays is not allowed. Please let me know if you can tell what the problem is. I've been racking my brains and I just can't see it :< Thank you!

#include <stdio.h>

void order(int a, int b);

int main(void)
{       
    int x, y, z;

    scanf("%d %d %d", &x, &y, &z);

    order(x, y);
    order(x, z);
    order(y, z);

    printf("%d %d %d", x, y, z);

    return 0;
}

void order(int a, int b)
{
    int inter;

    if(a > b)   
    { 
        inter = a;
        a = b;
        b = inter;
    }
}

Upvotes: 2

Views: 9463

Answers (1)

P.P
P.P

Reputation: 121397

You are passing the numbers x, y, and z by value. So the swap you do in order() will not reflect in main().

Instead pass the address of the variables and modify them so that original variables in main() reflect the changes you did in order():

#include <stdio.h>

void order(int *a, int *b);

int main(void)
{       
    int x, y, z;

    scanf("%d %d %d", &x, &y, &z);

    order(&x, &y);
    order(&x, &z);
    order(&y, &z);

    printf("%d %d %d", x, y, z);

    return 0;
}

void order(int *a, int *b)
{
    int inter;

    if(*a > *b)   
    { 
        inter = *a;
        *a = *b;
        *b = inter;
    }
}

Upvotes: 5

Related Questions