The best solution is the use of vectors. Follow the example:
To use the code, just copy the snippets inside the code boxes and paste them in order.
#include <stdio.h>
int main(int argc, char **argv){
const int NUM = 3; // quantidade de valores lidos
Has 2 vectors with 3 spaces the n and ord. The variable n will store the entered numbers, and ord will store the numbers ordered increasing.
int n[NUM];
int ord[NUM];
int x,y;
for(x=0; x<NUM; x++){
scanf("%d",&n[x]);
ord[x] = n[x];
}
The values read in n are already inserted in ord, this will facilitate when ordering the vector.
int min; // numero mínimo
int pos; // posição do número mínimo
for(x=0; x<NUM; x++){
min = ord[x];
pos = -1;
The variable min will always receive the position x of ord, because it will always be the first number of the vector, thus being the smallest number found so far.
And pos receives -1 to indicate that it is not related to any vector position.
for(y=x; y<NUM; y++){
When you find another value less than min, is recorded its value and its position.
if(ord[y] < min){
min = ord[y];
pos = y;
}
}
When as found a number smaller than the min, pos shall be greater than or equal to 0, then enter this condition to make the exchange of values.
if(pos >= 0){
ord[pos] = ord[x];
ord[x] = min;
}
}
printf("%d %d %d\n", ord[0], ord[1], ord[2]);
printf("%d %d %d\n", n[0], n[1], n[2]);
return 1;
}
Your code reads the values but does not sort in ascending order as it is requested, when writing the numbers, both will be in the same order.
– Brumazzi DB
I imagined that the author of the question had no problem with the ordination, since he himself stated that it worked. : D
– mau humor
It’s that sorting 2 or 3 numbers is easy, but above said is not feasible with conditions, so it uses sorting algorithms. If in a VC response you can give solutions and improvements, this results in the quality of your response.
– Brumazzi DB