#include <stdio.h>
int main() {
int a[100];
int x, n = 0;
scanf("%d", &x);
while (x > 0) {
a[n] = x % 10;
n++;
x = x / 10;
}
n = n - 1;
int n_max, c;
for (int i = 0; i < n - 1; i++) {
n_max = i;
for (int j = i + 1; j < n; j++) {
if (a[n_max] < a[j]) {
n_max = j;
}
}
if (n_max != i) {
c = a[i];
a[i] = a[n_max];
a[n_max] = c;
}
}
for (int i = 0; i < n; i++) {
printf("%d", a[i]);
}
return 0;
}
This code reads an integer, extracts its digits into an array in reverse order, then sorts those digits in descending order using selection sort, and prints the sorted digits. However, there is an issue with the loop bounds that causes the last digit to be skipped.
- The outer loop in the sorting section goes from i=0 to i < n-1, but after the while loop, n is set to the number of digits minus 1. This means the sorting loop only processes up to the second-to-last digit, leaving the last digit unsorted and unprinted.
- The final printing loop also uses i < n, which after n = n - 1 will print one fewer digit than originally stored.