Home C program to print all numbers with different digits in interval

# C program to print all numbers with different digits in interval

Just Steve
1#
Just Steve Published in 2018-01-12 19:03:50Z
 I need to make a program in C, which outputs all numbers with different digits in interval entered by the user. Here is what I've come up with. #include int main(){ int n, m, k = 0, p, flag, last, temp; do{ printf("Enter m and n (m < n):\n"); scanf("%d %d", &m, &n); if (m < n) { break; } else printf("\Error- m > n! Try again.\n\n"); } while (k == 0); printf("Numbers are:\n"); for (k = m; k <= n; k++) { p = k; flag = 0; if (p < 10) { flag = 1; } last = (p / 10) % 10 ; while (p > 0) { temp = p % 10; p = p / 10; if (temp == last ){ flag = 1; } last = temp; } if (flag != 1) { printf("%d ", k); } } getch(); return 0; }  Example output: Enter m and n (m < n): 100 130 Numbers are: 101 102 103 104 105 106 107 108 109 120 121 123 124 125 126 127 128 129 130  So the problem in this case is that it outputs 101 and 121. It shouldn't because they have two same digits. How do I fix that?
Jango
2#
 I believe this is the solution you're looking for. If you convert the numbers into strings it will be easier to check their digits. Note that you need two loops per number in the sequence. It's concise but it's still expensive. (Compile it using the flag -std=c11.) #include #include int main() { printf("Enter two non-negative numbers in ascending order:\n"); int min, max; scanf("%d %d", &min, &max); while(min < 0 || max < 0 || min > max) { printf("Invalid input! Please enter two non-negative numbers in ascending order:\n"); scanf("%d %d", &min, &max); } printf("The numbers without repeated digits in the interval [%d, %d] are:\n", min, max); for(int n = min; n <= max; ++n) { char digits[32]; sprintf(digits, "%d", n); int repeated = 0; for(int i = 0; digits[i] && !repeated; ++i) { for(int j = i + 1; digits[j]; ++j) { if(digits[i] == digits[j]) { repeated = 1; break; } } } if(!repeated) printf("%d ", n); } printf("\n"); return 0; } 
 Finally made it to work! int main(){ int n, m, k = 0, p = 0, flag, i = 0, j, dig[10]; do{ printf("Enter m and n (m < n):\n"); scanf("%d %d", &m, &n); if (m < n) { break; } else printf("\Error- m > n! Try again.\n\n"); } while (k == 0); printf("Numbers in the interval [%d, %d] are:\n", m, n); for (k = m; k <= n; k++){ p = k; flag = 0; dig[i] = 0; i = 0; if (p < 10){ continue; } while (p > 0){ dig[i] = p % 10; p = p / 10; i++; } dig[i] = -1; for (i = 0; dig[i] > -1; i++){ for (j = i + 1; dig[j] > -1; j++){ if (dig[i] == dig[j]){ flag = 1; } } } if (flag == 0){ printf("%d\t", k); } } getch(); return 0; }