#How to "mark" or "keep" elements of an array?

35 messages · Page 1 of 1 (latest)

stable delta
#

The task is to take array size (n) and array elements from stdin. Then check if the element is divisible by its last digit and then output only those elements. I can't use an extra array for this.

#include <stdio.h>
#include <stdlib.h>
#define MAX 100

int main()
{
    int n;
    int a[MAX];
    printf("Enter array length:\n");
    scanf("%d", &n);
    if(n <= 0 || n > MAX)
    {
        printf("Err");
        exit(EXIT_FAILURE);
    }
    for(int i = 0; i < n; i++)
    {
        scanf(" %d", &a[i]);
        int last_digit = a[i] % 10;
        if(a[i] % last_digit == 0)
        {
            printf("%d ", a[i]);
        }
    }
    printf("\n");

    exit(EXIT_SUCCESS);
}

So I'm stuck at the point where I somehow need to mark positions of these digits and keep them or alternatively remove those that don't fit the criteria. Also, there are negative numbers in the array.

honest carbonBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

coral sedge
#

You don't have to check right when you input the elements.

stable delta
#

Example:
Input: n = 9
a: 173 -25 23 7 17 25 34 61 -4612

Output: -25 7 25 61 -4612

stable delta
coral sedge
#

No, I mean that you just finish inputting the array, then iterate over it and check each element to output.

stable delta
coral sedge
#

No.

#

First of all, keep only the code that inputs each element in your current for loop.

stable delta
#

ye lol just a printf would do the trick

ebon musk
stable delta
ebon musk
stable delta
#

Okay I found a way

#

how to mark the array elements

#

not just for this task but for any essentially

#
int func(int array[], int arrayLen)
{
    int i, j, num;
    j = 0;

    for(i = 0; i < n; i++)
    {
        num = abs(array[i]) % 10;

        if(num == 0 || array[i] % num == 0)
        {
            array[j] = array[i];
            j++
        }
    }
    return j;
}
#

so the new array length will be j

compact osprey
compact osprey
lethal fjord
compact osprey
lethal fjord
#

And... i think i will repeat this again and again, the usage of scanf in the main is currently unsafe xD

lethal fjord
compact osprey
compact osprey
lethal fjord
lethal fjord
compact osprey
#

but imo, just printf is enough no need to overwrite the original array

stable delta
stable delta
stable delta
#

!solved