How to fill an array with 1 and 0 in random locations with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h> // For rand() and srand()
#include <time.h>   // For time()

#define SIZE 10

void FillArrayWithRandom1and0(int array[]) {
    // Seed the random number generator
    srand(time(0));

    // Fill the array with random 1s and 0s
    for (int i = 0; i < SIZE; ++i) {
        array[i] = rand() % 2; // Generates either 0 or 1
    }
}

int main() {
    int array[SIZE] = { 0 };

    FillArrayWithRandom1and0(array);

    for (int i = 0; i < SIZE; ++i) {
        printf("%d ", array[i]);
    }

    return 0;
}


 
/*
run:
 
0 1 1 0 0 1 1 1 0 0 
  
*/

 



answered Jan 24, 2025 by avibootz

Related questions

1 answer 77 views
1 answer 75 views
1 answer 99 views
1 answer 96 views
1 answer 93 views
1 answer 91 views
...