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

1 Answer

0 votes
using System;

public class FillArrayWith1And0InRandomLocations {
    static void FillArrayWithRandom1and0(int[] array) {
        Random rand = new Random();
        int len = array.Length;

        for (int i = 0; i < len; i++) {
            array[i] = rand.Next(2); // Generates either 0 or 1
        }
    }

    public static void Main(string[] args) {
        int size = 10; 
        int[] array = new int[size];
        
        FillArrayWithRandom1and0(array);

        foreach (int num in array) {
            Console.Write(num + " ");
        }
    }
}

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

 



answered Jan 25, 2025 by avibootz

Related questions

1 answer 73 views
1 answer 97 views
1 answer 94 views
1 answer 90 views
1 answer 89 views
...