0
0
R Programmingprogramming~15 mins

Repeat loop with break in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Repeat Loop with Break in R
📖 Scenario: You are counting the number of times you toss a coin until you get heads.
🎯 Goal: Build a program that uses a repeat loop to simulate tossing a coin repeatedly and stops when it lands on heads.
📋 What You'll Learn
Create a variable tosses to count the number of coin tosses
Create a variable coin to store the result of each toss
Use a repeat loop to simulate tossing the coin
Use break to stop the loop when the coin lands on heads
Print the total number of tosses after the loop ends
💡 Why This Matters
🌍 Real World
Counting attempts until success is common in games, simulations, and quality testing.
💼 Career
Understanding loops and breaking conditions is essential for automating tasks and controlling program flow.
Progress0 / 4 steps
1
Create the toss counter
Create a variable called tosses and set it to 0 to count the number of coin tosses.
R Programming
Need a hint?

Use the assignment operator <- to create the variable.

2
Set up the coin toss variable
Create a variable called coin and set it to an empty string "" to store the result of each toss.
R Programming
Need a hint?

Use "" to represent an empty string in R.

3
Write the repeat loop with break
Write a repeat loop that does the following:
1. Increase tosses by 1.
2. Randomly assign coin to either "Heads" or "Tails" using sample(c("Heads", "Tails"), 1).
3. Use if to check if coin is "Heads" and use break to stop the loop if true.
R Programming
Need a hint?

Use sample(c("Heads", "Tails"), 1) to simulate a coin toss.

4
Print the total tosses
Write a print statement to display the total number of tosses stored in tosses.
R Programming
Need a hint?

Use print(tosses) to show the number of tosses.