microsoft/qdk

Public

mirrored fromhttps://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
billti/wgpu

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

samples/language/ConditionalBranching.qs

41lines · modecode

1/// # Sample
2/// Conditional Branching
3///
4/// # Description
5/// Q# supports three branching keywords: `if`, `elif`, and `else`. These behave in the normal
6/// way, if you're familiar with if expressions or statements in other languages. One key distinction
7/// in Q# is that ifs are expressions, not statements. That means that they can return values, and
8/// they effectively perform the job of both ternary expressions and if statements in other languages.
9/// If expressions allow your code to branch, or conditionally execute parts of a Q# program.
10namespace MyQuantumApp {
11 @EntryPoint()
12 operation Main() : Unit {
13 let number = 5;
14 // Conditionally messages "Fizz" if the `number`, in this case 5, is divisible by 3.
15 // Since 5 is not divisible by 3, the message "Fizz" will not be printed.
16 if number % 3 == 0 { Message("Fizz"); }
17
18 // Conditionally messages "Buzz" if the `number`, in this case 5, is divisible by 5.
19 // Since 5 is divisible by 5, the message "Buzz" will be printed.
20 if number % 5 == 0 { Message("Buzz"); }
21
22 let fahrenheit = 40;
23
24 // In this example, we print a message based on the temperature. The
25 // message that will be printed is "It is livable".
26 // `elif` allows you to express successive conditional expressions, with each
27 // successive condition only being evaluated if the previous one was false.
28 if fahrenheit <= 32 {
29 Message("It's freezing");
30 } elif fahrenheit <= 85 {
31 Message("It is livable");
32 } else {
33 Message("It is way too hot");
34 }
35
36 let fahrenheit = 40;
37
38 // `if` can also be used as an expression, to conditionally return a value.
39 let absoluteValue = if fahrenheit > 0 { fahrenheit } else { fahrenheit * -1 };
40 }
41}
42