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

1 Answer

0 votes
#include <iostream>
#include <cstdlib> // For rand() and srand()
#include <ctime>   // For time()

#define SIZE 10

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

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

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

    FillArrayWithRandom1and0(array);

    for (int i = 0; i < SIZE; ++i) {
        std::cout << array[i] << " ";
    }
}


 
/*
run:

1 0 0 1 1 0 1 0 0 0 
  
*/

 



answered Jan 24, 2025 by avibootz

Related questions

1 answer 92 views
1 answer 65 views
1 answer 99 views
1 answer 96 views
1 answer 93 views
1 answer 91 views
...