If you succeeded in writing this code by yourself, you are on the right path, if you didn’t, don’t worry, just follow the solution with me so you can catch up!
Let’s go over what was asked to do first.
We need two variables and the exercise seems like a “logical” light powered by a battery with the two poles being Positive and Negative variables.
Keep in mind that a Boolean variable can only have two values technically, True and False.
Next we have four conditions on which we can build our If statement:
Positive and negative are true -> Display in console: The light is on.
Positive is true but negative is false -> Display in console: The light is off.
Positive is false and negative is true -> Display in console: The light is off.
In any other case -> Display in console: Please plug both cables to turn the light on.
Note that all the possibilities of the truth table are covered here. They are (1,1), (1,0), (0,1) and (0,0). Not sure what a truth table is? You can just skip this statement and read the code below.
Option Explicit On Option Strict On Module Program Sub Main() 'Declaration Dim Positive As Boolean Dim Negative As Boolean 'Initialization Positive = False Negative = False 'Condition If Positive = True And Negative = True Then Console.WriteLine("The light is on.") ElseIf Positive = False And Negative = True Console.WriteLine("The light is off.") ElseIf Positive = True And Negative = False Console.WriteLine("The light is off.") Else Console.WriteLine("Please plug both cables to turn the light on.") End If Console.ReadKey() End Sub End Module
We have three parts in this solution, first the declaration of both Positive and Negative variables. Second we assign values to these two variables and third, we complete the conditional verification on the variables (Condition section).
The condition section (If)
This is the portion of the code we want to analyze because it contains an If statement.
In the first condition check, we go through Positive = True and Negative = True which is the first condition in our list -> Positive and negative are true -> Display in console: The light is on.
We then have an ElseIf, meaning that if the first condition did not pass and entered the Console.WriteLine block, we will have to check this ElseIf. Positive is False and Negative is True.
The same thing occurs for the third condition check (ElseIf).
Finally, our else will catch everything that has not passed the first three conditions which should be: Positive is False and Negative is False.
You should test all the possible values to make sure your code works properly.
In the next tutorial I will show you a really good way to take control of what is going on in your code, something teachers normally show at the end of the first Programming Course!