**Monte Carlo** is an algorithm for computers, it tells the behavior of other programs that is it is used to find answers to different types of questions although it is not an exact method or exact calculation but instead it uses randomness and statistics to get a result. It uses random numbers instead of fixed inputs and its main purpose is to find probability by computing the random inputs.

We start with including the header files in the program “stdio.h”, ”conio.h” and “stdlib.h”.

In this example we have taken a sample of probability. This program shows the probability of getting a 3 heads,6 heads or 9 heads if a coin is tossed 10 times and this process if repeated x times to get an approximate result.

We start with entering the limit or the number of times the whole process will be repeated.

1 2 |
printf("enter the limit amount"); scanf("%d",&limit); |

A while loop will be used to continue the process x times and then a for loop will be used which depicts that a coin is tossed 10 times and inside the for loop a random number is generated every time.

1 |
y=(float)((rand()% 65535)/65535.0f)*10; |

What this statement does is that it initializes a value between 0 and 5 in variable “y”, then it checks in the value in y is less than half that is 2.5 then the coin is head and if it is more than half then it is a tail as chances of getting a head or tail in a coin toss is 50-50.

1 2 3 4 5 6 7 8 |
if (y<h) { head=head+1; } else { tail=tail+1; } |

If it is head then it gets added to variable “head” and after the end of for loop it is checked if the value of head is equal to 3,6 or 9 then variable “count” gets incremented.

1 2 3 4 |
if ((head==3) || (head==6) || (head==9)) { count=count+1; } |

The variable “h” is used to store the value 2.5 which is used to compare either it is a head or tail.

The variable “answer” is used to store the end result of the program, that is, it is used to find the probability by dividing the number of times 3, 6 or 9 heads have come (count) when a coin is tossed 10 times by the total number of time the whole process is repeated (limit).

And the answer is displayed on the output screen.

1 |
answer=(float)count/limit; |

I have used a coin toss probability example but you can also use Monte Carlo algorithm to find the value of pi, etc, the program is really simple you just need to understand the logic.

Download C Program: Simple Explanation On Monte Carlo Algorithm