2.4: if, else if, else
In this module we will go deeper into boolean logic and learn about the else if
and else
keywords.
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
0.02_Booleans_Conditionals
Write your code for this module within
Program.cs
of that project
Description
A conditional statement is a statement that can be executed based on a condition. Two different types of conditionals are looping and branching. Some different branching statements are switch cases, if statements, and ternary statements. Here we will go into some fun ways to move data around.
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.
Above, we checked to see if a number is equal to 50.
DataType
Name we associate to value we are declaring
Equals operator
We set
value
to 100 divided by 2. 50Declaring our if statement
Boolean condition asking if
value
is equal to 50Code executed if statement is true.
Let's take a look at some more boolean logic with if
, else if
, and else
.
Discussion
In the program above we have the user enter in a number.
It will then check if the number is 1.
If it is not one, it will check if it is 2.
If it is not 2, it will check if it is 3.
If it is none of the above, it will print Wrong Number.
Discussion
Above is an example of a program that uses if
, else if
, and else
statements with an 'is equal to' operator or ==
to display a result depending on what the user inputs. You can see the program checks whether the user's input is true or false compared to the different statements.
else if
statements are run if the previous if
statements are resulted to false. else
statements are run if all previous statements are resulted to 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 or are only wanting to get one result back from the branch. Consider the following:
Another Example
At Eleven Fifty, we believe that in order to gain literacy with code, you have to read as much code as you write. For the following exercise, coopy the code into a new console app called Bank_Pro
Next: Switch Statements
Last updated