7.2: If Statements
In this module we'll study if
, else if
, and else
statements.
File Location
Right click on the solution you made in the first module.
Go to Add > New Project and select Console App (.NET Framework).
Name it
07_conditionals_if_else
.Write your code for this module within
Program.cs
of that project.
If, Else If, and Else Statements
In the previous module on booleans, we got a brief introduction to some if
statements. if
statements check to see if a condition is true or false. We also gave a challenge in that module that would require you to use the else
& if else
keywords. Let's add some code that will allow us to write else if
statements:
Analysis
Here we set up a question in the console that asks a user to enter a value. We store that value in an integer variable.
We check if the number is 5. If it is we will execute another console statement. If the number is not 5 and the expression resolves to false, the program will continue to the
else if
statement.else if
statements are run if the previousif
statements are false. You can have as manyelse if
statements as you want.The
else
statement goes at the end. Similar to thedefault
in a switch,else
statements are run if all previous statements are false.
Multiple if statements
If you have multiple if
statements within a branch, your program will check all those if
statements even if a previous one resulted in true. Not a bad thing, but handy to know especially when you get into the speed of your application.
Add the following code in your Program.cs
file. But, before you run it, try to predict what will print and why.
Last updated