Yes, the code is right, but it is not readable, it is very easy to think that he does one thing and does another. Note that the code is the same, but it is simpler and more readable in the compact version and more explicit in the organization of the blocks. Even spaces make a difference in readability. And good names avoid comments.
Under normal conditions or before n
should never be less than 1, the if
only makes sense if you have error in the argument. And even if that comes, check and not check this way gives in the same. If it would be the case it exists if it is to give invalid argument error.
#include <stdio.h>
int EstaOrdemCrescente(int vetor[], int tamanho) {
for (int i = 1; i < tamanho; i++) if (vetor[i - 1] > vetor[i]) return 0;
return 1;
}
int main() {
printf(EstaOrdemCrescente((int[]){-1, 2, 3, 4, 5}, 5) ? "Esta em ordem crescente\n" : "Nao esta em ordem crescente\n");
printf(EstaOrdemCrescente((int[]){-1, 2, 0, 4, 5}, 5) ? "Esta em ordem crescente\n" : "Nao esta em ordem crescente\n");
printf(EstaOrdemCrescente((int[]){1}, 0) ? "Esta em ordem crescente\n" : "Nao esta em ordem crescente\n");
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
#include <stdio.h>
int EstaOrdemCrescente(int vetor[], int tamanho) {
for (int i = 1; i < tamanho; i++) {
if (vetor[i - 1] > vetor[i]) {
return 0;
}
}
return 1;
}
int main() {
printf(EstaOrdemCrescente((int[]){-1, 2, 3, 4, 5}, 5) ? "Esta em ordem crescente\n" : "Nao esta em ordem crescente\n");
printf(EstaOrdemCrescente((int[]){-1, 2, 0, 4, 5}, 5) ? "Esta em ordem crescente\n" : "Nao esta em ordem crescente\n");
printf(EstaOrdemCrescente((int[]){1}, 0) ? "Esta em ordem crescente\n" : "Nao esta em ordem crescente\n");
}
No, it doesn’t stop after the first two... I tested it with something like {1, 2, 3, 8, 4} and it really returns that it’s not ordered. Maybe I was a little confused by being without { no for and if (the function is not mine, it was given in the exercise, so I’m not understanding where the error is)
– Leila
tested my code too? Return to the function where it is and returns what was requested.
– dfop02