Numbers in Ascending Order C

1

I'm trying to make a code to show 3 random numbers in ascending order typed by the user however I do not understand why my code is not working

#include <stdio.h>

main(){

int numeros[3],a,b,c,maior=0,menor=0,medio=0;



printf("Digite 3 numeros:\n");
scanf("%d %d %d",&numeros[0],&numeros[1],&numeros[2]);


for(a=0;a<3;a++){
    if(numeros[a]>numeros[a+1]){
        numeros[a]=maior;
    }


}
for(b=0;b<3;b++){
    if(numeros[b]<numeros[b+1]){
        numeros[b]=menor;
    }
}
for(c=0;c<3;c++){
    if(numeros[c]<maior && numeros[c]>menor){
        numeros[c]=medio;
    }
}

printf("%d %d %d",menor,medio,maior);

output appears only 0 in all 3 positions.

    
asked by anonymous 17.03.2017 / 21:01

2 answers

1

Are you checking for errors?

In the ifs it will give an error by popping the array in "[a + 1]" and "[b + 1]": numeros[a]>numeros[a+1] and numeros[a]>numeros[b+1] .

You have reversed the value assignment:

numeros[a]=maior;
numeros[b]=menor;
numeros[c]=medio;

Change to:

maior=numeros[a];
menor=numeros[b];
medio=numeros[c];

You can also do this:

int i, j, a, n, number[30];

printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
    scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
    for (j = i + 1; j < n; ++j)
    {
        if (number[i] > number[j])
        {
            a =  number[i];
            number[i] = number[j];
            number[j] = a;
        }
    }
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
    printf("%d\n", number[i]);

Source: link

    
17.03.2017 / 21:22
3

This code is too complex, you do not need it all and I find the accepted answer even worse because it's a quadratic algorithm (not that it makes a lot of difference in such a simple case), so here's a simpler solution. If you want to use array yourself, which is unnecessary, just change the variables. If you want to do a loop also gives, but it gets more complicated and so it does not make sense.

#include <stdio.h>

int main() {
    int a, b, c;
    printf("Digite 3 numeros:\n");
    scanf("%d %d %d", &a, &b, &c);
    if (a > c) {
        int tmp = c;
        c = a;
        a = tmp;
    }
    if (a > b) {
        int tmp = b;
        b = a;
        a = tmp;
    }
    if (b > c) {
        int tmp = c;
        c = b;
        b = tmp;
    }
    printf("%d %d %d", a, b, c);
}

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

You can generalize a swap function to avoid these 3 swap lines, but in a simple example it does not even pay.

I always prefer to use the Occam Razor .

    
17.03.2017 / 21:31