Exercise - Complete a challenge activity using conditional operators
Code challenges will reinforce what you've learned and help you gain some confidence before continuing on.
Conditional operator challenge
In this challenge, you'll implement a conditional operator to simulate a "coin flip". The resulting decision logic will display either heads
or tails
.
Code challenge: write code to display the result of a coin flip
Here are your challenge requirements:
Ensure that you have an empty Program.cs file open in Visual Studio Code.
If necessary, open Visual Studio Code, and then complete the following steps to prepare a Program.cs file in the Editor:
On the File menu, select Open Folder.
Use the Open Folder dialog to navigate to, and then open, the CsharpProjects folder.
In the Visual Studio Code EXPLORER panel, select Program.cs.
On the Visual Studio Code Selection menu, select Select All, and then press the Delete key.
Use the
Random
class to generate a value.Consider the range of numbers that is required.
Based on the value generated, use the conditional operator to display either
heads
ortails
.There should be a 50% chance that the result is either heads or tails.
Your code should be easy to read, but with as few lines as possible.
You should be able to accomplish the desired result in three lines of code.
Whether you get stuck and need to peek at the solution or you finish successfully, continue on to view a solution to this challenge.