# Lesson 7: Conditionals

{% hint style="warning" %}
At the end of this lesson, you should be able to answer the following:

* How do I write a conditional statement in C#?
* What is an else clause?
  {% endhint %}

In life, we make decisions every moment. We can show this decision making process through a programming construct called a *conditional*.

### If statement

```csharp
var happy = true;

if (happy)
{
    Console.WriteLine("Clap your hands!");
}

Console.WriteLine("END");
```

The code above contains an *if* statement block. If the condition in the round brackets is **true**, the program will execute the statements in the curly brackets. Otherwise, it will just skip the block and go to the next statement after it.

Type the code above in the code box and run it. We should see two lines in the output, `Clap your hands!` followed by `END`.

![](https://3447149067-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdynmZrfNEt1WSSrlHq%2F-MeQ9jHuhAwI1D00XINX%2F-MeQAMd3JHoJLj2y4LKO%2F2021-07-13_0-39-44.png?alt=media\&token=40ae9bb6-fcb2-4c4b-b225-52932aa383f4)

Change the value of the variable `happy` to `false`, then run the program again.

![](https://3447149067-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdynmZrfNEt1WSSrlHq%2F-MeQ9jHuhAwI1D00XINX%2F-MeQAXcJ7e3RtF1v-9_9%2F2021-07-13_0-40-20.png?alt=media\&token=12ba10b6-40e8-480a-89e9-4fdc0d68bef4)

Now we don't see the `Clap your hands!` line printed anymore. This is because our condition is the value of `happy`. Since it is now false, our program does not run the lines inside the curly braces. Instead, it goes to the next statement, `Console.WriteLine("END");`.

We can also use expressions as the condition in the round brackets, as long as the expression's result is a `bool` value. Recall from [Lesson 3](https://codingmama.gitbook.io/csharp-for-beginners/lesson-3-data-types#boolean) that `bool` or Boolean values have only two possible values, `true` or `false`. Lesson 4 has a list of [comparison](https://codingmama.gitbook.io/csharp-for-beginners/lesson-4-operators#comparison-operators) and [logical](https://codingmama.gitbook.io/csharp-for-beginners/lesson-4-operators#logical-operators) operators that we can use to make expressions.

```csharp
var password = "abc123";

if (password.Length < 8)
{
    Console.WriteLine("Your password is too short!");
} 
```

The example above checks the length of a password. In [Lesson 6](https://codingmama.gitbook.io/csharp-for-beginners/tutorial/lesson-6-strings) we learned how to get the length of a string, by calling `.Length`. The result is an `int` value which we can now compare with another integer, `8`.

We can even nest if statements, by putting another if statement inside the statement block.

Type the code below into a code box and run the program. Try changing the values of `passedFirstTest`, `passedSecondTest`, and `passedThirdTest` to see the different outputs you can make.

```csharp
var passedFirstTest = true;

if (passedFirstTest)
{
    Console.WriteLine("You've passed the first test!");
    
    var passedSecondTest = true;
    
    if (passedSecondTest)
    {
        Console.WriteLine("You've passed the second test!");
        
        var passedThirdTest = true;
        
        if (passedThirdTest)
        {
            Console.WriteLine("Congratulations! You passed all the tests!");
        }
    }
}
```

![Output of the program above](https://3447149067-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdynmZrfNEt1WSSrlHq%2F-MeQ9jHuhAwI1D00XINX%2F-MeQAmxytVsX7KsaYdbK%2F2021-07-13_0-41-10.png?alt=media\&token=b34c6e65-6655-4bc8-9abd-6677b348d48f)

As you may have noticed, we indent the statements inside the curly brackets. It's not required by C#, but it makes it easier to see which statements are part of which if block. Otherwise, the code can become unreadable, causing all sorts of program errors!

### Else clause

When we make a choice, often there is an alternate path that happens if the condition isn't true. We can show this in our code through the *else* clause. The *else* clause is an optional addition to an *if* statement.

An *if* statement doesn't always have to have an *else* clause, but an *else* clause can't exist without an *if* statement.

```csharp
var age = 20;

if (age < 16)
{
    Console.WriteLine("You're not allowed to drive yet.");
}
else
{
    Console.WriteLine("You're allowed to drive.");
}
```

The code above is checking the value of `age`. If `age` is less than `16`, the text `You're not allowed to drive yet` is displayed. Otherwise, `You're allowed to drive` is shown.

![](https://3447149067-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdynmZrfNEt1WSSrlHq%2F-MeQ9jHuhAwI1D00XINX%2F-MeQAu7nT3yawD8ZQgnl%2F2021-07-13_0-42-22.png?alt=media\&token=91c4d6fa-ef3c-4647-9ae6-fa1e024241ed)

We can also nest another if statement inside the else clause, if we wanted to check for more conditions.

```csharp
var age = 20;
var hasLicence = false;

if (age < 16)
{
    Console.WriteLine("You're not allowed to drive yet.");
}
else
{
    if (hasLicence)
    {
        Console.WriteLine("You're allowed to drive.");
    }
    else
    {
        Console.WriteLine("You need to have a licence to drive.");
    }    
}
```

![Output of the program above, with a nested if statement inside the else clause](https://3447149067-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdynmZrfNEt1WSSrlHq%2F-MeQ9jHuhAwI1D00XINX%2F-MeQB0htQ1Y5iAx1k1oi%2F2021-07-13_0-43-16.png?alt=media\&token=0fdcf2c8-2cac-4e34-9117-816b8c98988c)

C# has special syntax to make this code more concise and readable. We can put the nested if statement on the same level as the else, creating an *else-if* clause.

```csharp
var age = 20;
var hasLicence = false;

if (age < 16)
{
    Console.WriteLine("You're not allowed to drive yet.");
}
else if (hasLicence)
{
    Console.WriteLine("You're allowed to drive.");
}
else
{
    Console.WriteLine("You need to have a licence to drive.");
}
```

![The same output, with different syntax](https://3447149067-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdynmZrfNEt1WSSrlHq%2F-MeQ9jHuhAwI1D00XINX%2F-MeQBDwUpvd-Z0s63ia5%2F2021-07-13_0-43-45.png?alt=media\&token=0115b63f-f9c0-4282-97e8-69e3daa64c53)

{% hint style="info" %}
**Question**

What will be the output when this program is run?

```csharp
var isHappy = true;
var isKnown = false;

if (isHappy && isKnown)
{
    Console.WriteLine("Clap your hands!");
}

Console.WriteLine("END");
```

{% endhint %}

{% hint style="info" %}
**Questions**

True or False:

1. You can put arithmetic expressions (e.g. `10 + 5`) as the condition of an if statement.
2. An else clause can only exist as part of an if statement.
3. You can put an if statement inside another if statement.
4. You can't put an if statement inside an else clause.
   {% endhint %}

{% hint style="info" %}
**Challenge**

Let's make songs into code! Did you guess which popular song our sample code was about? If you guessed "If You're Happy And You Know It", you're correct!

For this challenge, find a popular song with a conditional and try to represent it as code! Turn the "if" part into an if statement, and the rest into a `Console.WriteLine()`statement.

Example songs:

* "If You Leave Me Now" by Chicago
  * *If you leave me now, you'll take away the biggest part of me*
* "If I Ain't Got You" by Alicia Keys
  * *But everything means nothing, if I ain't got you*
* "I Will Always Love You" by Whitney Houston
  * *If I should stay, I would only be in your way*
* "Time After Time" by Cyndi Lauper
  * *If you're lost, you can look and you will find me*
  * *If you fall, I will catch you, I will be waiting*
    {% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://codingmama.gitbook.io/csharp-for-beginners/tutorial/lesson-7-conditionals.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
