Print an array with numbers having 1, 2 and 3 as a digit in ascending order

In this problem, we need to find and print all numbers from an array that contain the digits 1, 2, and 3. The numbers should be printed in ascending order. If no such numbers exist, we return -1.

Syntax

// Check if number contains digits 1, 2, and 3
int containsAllDigits(int num);

// Sort and filter array elements
void printNumbersWithDigits(int arr[], int n);

Algorithm

The approach involves the following steps −

  • Step 1: Sort the array in ascending order
  • Step 2: For each number, convert it to string format
  • Step 3: Check if the string contains digits '1', '2', and '3'
  • Step 4: Print numbers that contain all three digits
  • Step 5: If no such numbers found, print -1

Example

Here's a complete C program to solve this problem −

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int containsAllDigits(int num) {
    char str[20];
    sprintf(str, "%d", num);
    
    int has1 = 0, has2 = 0, has3 = 0;
    
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == '1') has1 = 1;
        if (str[i] == '2') has2 = 1;
        if (str[i] == '3') has3 = 1;
    }
    
    return has1 && has2 && has3;
}

int main() {
    int arr[] = {320, 123, 124, 125, 14532, 126, 340, 123400, 100032, 13, 32, 3123, 1100};
    int n = sizeof(arr) / sizeof(arr[0]);
    int found = 0;
    
    // Sort the array in ascending order
    qsort(arr, n, sizeof(int), compare);
    
    printf("Numbers containing digits 1, 2, and 3: ");
    
    for (int i = 0; i < n; i++) {
        if (containsAllDigits(arr[i])) {
            printf("%d ", arr[i]);
            found = 1;
        }
    }
    
    if (!found) {
        printf("-1");
    }
    
    printf("<br>");
    return 0;
}
Numbers containing digits 1, 2, and 3: 123 3123 14532 100032 123400

How It Works

  1. Sorting: The qsort() function sorts the array in ascending order using a comparison function.
  2. Digit Check: The containsAllDigits() function converts each number to a string and checks for the presence of digits '1', '2', and '3'.
  3. Output: Numbers that contain all three required digits are printed in sorted order.

Key Points

  • The sprintf() function converts integer to string for digit checking
  • The algorithm has O(n log n) time complexity due to sorting
  • All three digits (1, 2, 3) must be present in a number for it to be included

Conclusion

This solution efficiently finds and prints all numbers containing digits 1, 2, and 3 in ascending order. The approach uses string conversion for digit checking and qsort for ordering the results.

Updated on: 2026-03-15T11:06:15+05:30

805 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements