Search code examples
arraysclogic

How to print elements of an array except those containing a specific digit?


I just started learning C language and I made this program which prints elements of an array in descending order and then print the 2-digit elements of the same array in descending order. Now I want to print elements of that array except those which contain the digit 5. This is the program I made:

#include<stdio.h>
#include<conio.h>
int main(void)
{
    int array[20] = {2,5,1,3,4,10,30,50,40,20,70,90,80,60,100,150,130,110,120,140};

    printf("original array:\n");

    for(int i=0;i<20;i++)
    {
        printf("%i\n", array[i]);
    }

// To sort elements of array in descending order

int i,j,temp;

for(i=0;i<20;i++)
{
        for(j=i+1;j<20;j++)
        {
           if(array[i]>array[j])
           {
               temp = array[i];

               array[i] = array[j];

               array[j] = temp;
           }
        }
}

// Now to print the sorted array

printf("arranged array in descending order:\n");

for(int x = 19;x>=0;x--)
{
    printf("%i\n", array[x]);
}

// To print only 2-digit elements of the array

printf("following are only 2-digit elements of array in descending order:\n");

for(int k = 19;k>=0;k--)
{
    if(array[k]>9 && array[k]<100)
    {
        printf("%i\n", array[k]);
    }
}
}

What logic should I make so that only elements containing '5' are not printed? Thanks in advance :)


Solution

  • Use functions to better organize your code. First, define a swap() function:

    void swap(int *a, int *b)
    {
        int tmp = *a;
        *a = *b;
        *b = *a;
    }
    

    Then, write a sorting algorithm. To follow your case:

    void bubble_sort(int *array, int size)
    {
        int i, j, swap_oper;
        for (i = 0; i < size - 1; ++i) {
            swap_oper = 0;
    
            for (j = 0; j < size - i - 1; ++j) {
                if (array[j] > array[j+1]) {
                    swap(&array[j], &array[j+1]);
                    swap_oper = 1;
                }
            }
    
            if (swap_oper == 0)
                break;
        }
    }
    

    To print all numbers except those containing 5, define a function that checks whether a number has 5s in it:

    int contains_five(int n)
    {
        while (n != 0) {
            if (n % 10 == 5)
                return 1; // true
    
            n /= 10;
        }
        return 0; // false
    }
    

    Then you can use it like this:

    void print_array(int *array, int size)
    {
        int i;
        for (i = 0; i < size; ++i) {
            if (!contains_five(array[i]))
                printf("%d ", array[i]);
        }
    }