# Monte Carlo Sim for Coin Toss in R [closed]

I'm trying to answer the following simple probability question but using a monte carlo type simulation function in R: A fair coin is flipped 100 times. Find the probability that the number of times it shows heads is exactly equal to 40.

I'm pretty new to simulations and to writing functions in R, so I'm at a lot of a loss.

I know I can do this to simulate finding the percent heads flipped in a given sample of coin tosses:

    flip_function <- function(n) {
flips <- sample(c("heads", "tails"), n, replace=TRUE)
}


I know I'll need to use a for loop but my best guess is just wrong (in fact it returns an error saying I have an excessive } which I also don't understand):

counter = 0
flip_function <- function(n){
for(i in 1:n){
flips <- sample(c("heads", "tails"), 100, replace=TRUE)
counter = counter + 1
}
}


Any help would really be appreciated. Thanks!

Do you have the vector percent_heads initialized elsewhere? If you mean to have it completely contained within the function it must be initialized outside the for loop. I took your code outside the function and it seems to work okay with some minor changes (your return statement is missing 2 brackets -- likely the source of your error).

n <- 10000