V
V
Vladimir Rudometkin2018-11-08 10:23:23
C++ / C#
Vladimir Rudometkin, 2018-11-08 10:23:23

How to remove all array elements less than a specified number in C?

Hello. Stuck on a certain task. No solution comes to mind. If you have sufficient experience, I will be very grateful if you enlighten me. The connected libraries are not printed for some reason.
Given an array a1, a2...an. Develop a program to remove all elements from an array less than a given value b.

code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
    srand(time(NULL));
    
    int a, b, g;
    
    scanf("%d", &a);
     b = 4;
    
    int x[a];
    
    
    for (int i = 0; i < a; i++){
        x[i] = 0 + rand() %10;
    }
    
    for(int i = 0; i < a; i++){
        if(x[i] < b){
        g++;
        }
    int z[g];
    
    for(int i = 0; i < g; i++){
        z[i] = 
    
    }
    printf("Было\n");
    for (int i = 0; i < a; i++){
        printf("x[%d] = %d\n", i, x[i]);
    }
    printf("Стало\n");
    for (int i = 0; i < a; i++){
        printf("z[%d] = %d\n", i, z[i]);
    }
    
    
    
    
    return 0;
}


I understand that I probably went the wrong way, but I just wanted it to work. I study and write in pure C. At the moment where the check in the loop I don’t know what to write. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2018-11-08
@spezcial

There are actually many options. As for me, the simplest (for understanding) is:
1. Walk through the array and count how many "unnecessary" elements are in it
2. Create a new array with the size "size_of_previous_number_of_unnecessary_elements"
3. We go through the array again and copy only desired elements
Not the best option, since we have two passes through the array. You can get by with one (for example, copying the values ​​from the end of the array and remembering the number of elements found, so that you can trim the array correctly later), but the logic will be a little more complicated and confusing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question