C Program to Generate a Random Subset by Coin Flipping

«
»
This is a C Program to generate a random subset by flipping coin. Basic idea is to generate randomly number either 0/1, if the number is zero print the subset.

Here is source code of the C Program to Generate a Random Subset by Coin Flipping. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `#include<stdio.h>`
2. `#include<math.h>`
3. `#include<time.h>`
4. `#include<stdlib.h>`
5. ` `
6. `int coinFlip() {`
7. `    time_t seconds;`
8. `    time(&seconds);`
9. `    srand((unsigned int) seconds);`
10. `    return rand() % 2;`
11. `}`
12. ` `
13. `int main(int argc, char **argv) {`
14. `    int i;`
15. `    time_t seconds;`
16. `    time(&seconds);`
17. `    srand((unsigned int) seconds);`
18. ` `
19. `    printf("Enter the number of elements in the set: ");`
20. `    int N;`
21. `    scanf("%d", &N);`
22. `    int sequence[N];`
23. ` `
24. `    for (i = 0; i < N; i++)`
25. `        sequence[i] = rand() % (50 - 1 + 1) + 1;`
26. ` `
27. `    printf("The elements in the set : ");`
28. `    for (i = 0; i < N; i++)`
29. `        printf("%d ", sequence[i]);`
30. ` `
31. `    printf("\nThe random subset is: \n{ ");`
32. `    for (i = 0; i < N; i++)`
33. `        if (coinFlip() == 1)`
34. `            printf("%d ", sequence[i]);`
35. `    printf("}");`
36. `    return 0;`
37. `}`

Output:

```\$ gcc CoinFlipping.c
\$ ./a.out

Enter the number of elements in the set: 5
The elements in the set : 31 5 13 28 33
The random subset is:
{ 31 5 13 28 33 }```

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!