microsoft/qdk

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
20c2fb1c118e553b69d042c5289d61dda9c55e76

Branches

Tags

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

Clone

HTTPS

Download ZIP

samples/language/ConditionalBranching.qs

38lines · 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.
10
11function Main() : Unit {
12 let number = 5;
13 // Conditionally messages "Fizz" if the `number`, in this case 5, is divisible by 3.
14 // Since 5 is not divisible by 3, the message "Fizz" will not be printed.
15 if number % 3 == 0 { Message("Fizz"); }
16
17 // Conditionally messages "Buzz" if the `number`, in this case 5, is divisible by 5.
18 // Since 5 is divisible by 5, the message "Buzz" will be printed.
19 if number % 5 == 0 { Message("Buzz"); }
20
21 let fahrenheit = 40;
22
23 // In this example, we print a message based on the temperature. The
24 // message that will be printed is "It is livable".
25 // `elif` allows you to express successive conditional expressions, with each
26 // successive condition only being evaluated if the previous one was false.
27 if fahrenheit <= 32 {
28 Message("It's freezing");
29 } elif fahrenheit <= 85 {
30 Message("It is livable");
31 } else {
32 Message("It is way too hot");
33 }
34 let fahrenheit = -40;
35 // `if` can also be used as an expression, to conditionally return a value.
36 let absoluteValue = if fahrenheit > 0 { fahrenheit } else { fahrenheit * -1 };
37 Message($"Absolute value of {fahrenheit} is {absoluteValue}");
38}
39