Home > Enterprise >  How to append elements to an array in a program in C?
How to append elements to an array in a program in C?

Time:11-14

I want the user to input values of elements to an array of 10 ints. Then I want to print out all the indexes of the values of the elements which when divided by 5 give 0.

I've tried doing it like this, but it's not working. How do I append the i's into an array?

#include <stdio.h>

#define N 10

int main()
{
    int a[10];
    int i;
    int index[10] = {};

    printf("Input %d values into the array:\n", N);
    for (i = 0; i < N; i  ){
        scanf("%d", &a[i]);
        if (a[i] % 5 == 0){
            index[10]  = i;
        }
    }

    printf("%d", index);
    return 0;
}

CodePudding user response:

You can create a new index for the second array and solve the problem. But is better to make it in different loops.

 #include <stdio.h>
    
    #define N 10
    
    int main()
    {
    
    int a[N];
    int index[N] = {};
    //o will be the index for index array
    int o = 0;
    
    printf("Input %d values into the array:\n", N);
    for (int i = 0; i < N; i  ){
        scanf("%d", &a[i]);
    
        if (a[i] % 5 == 0){
            index[o] = i;
            o  ;
        }
    }
    
    for(int i = 0; i<o;i  ){
        printf("%i",index[i]);
    }
    return 0;
    
    }

CodePudding user response:

Your last comment clarified the intention of your code so here is how solve it directly without the restoring to dynamic memory allocation:

#include <stdio.h>
#define N 10

int main(void) {
    int result[N];
    int n = 0;
    for (int i = 0; i < N; i  ){
        int d;
        if(scanf("%d", &d) != 1) {
            printf("scanf failed\n");
            return 1;
        }
        if (!(d % 5)) {
            result[n  ] = i;
        }
    }
    for(int i = 0; i < n; i  ) {
        printf("%d%s", result[i], i   1 < n ? "," : "\n");
    }
}

and example run:

echo "1 2 3 4 5 6 7 8 9 10" | ./a.out
4,9
  •  Tags:  
  • c
  • Related