Logical operators in CSharp
In this article, you will learn about the programming with relative and logical operators. Because, as you have already learned in the last article about decisions, decisions are made on comparisons. So far we have only used ==. However, there are many more operators that help you make your decisions (and thus if statements) even more complex
List of logical operators
Operator | C, C++, C#, Java, PHP | |||||||
---|---|---|---|---|---|---|---|---|
Comparisons | higher | > | ||||||
lower | < | |||||||
higher or equal | >= | |||||||
lower or equal | <= | |||||||
equal | == | |||||||
not equal | != | |||||||
Connective | And (Conjunction) | && | ||||||
Or (Disjunction) | || | |||||||
Not (Negation) | ! |
You can now use this as a basis for your If statements. Example weather. You want to be clothed based on how warm it is either a TShirt, asweater, or a jacket . (Previous ones included).
Example of logical operators in C #
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panjutorials { class Program { static void Main(string[] args) { int temperature = 15; if(temperature > 23) { Console.WriteLine("Tshirt is enough"); } else if(temperature > 18) { Console.WriteLine("Pullover should do it"); } else if(temperature <= 18) { Console.WriteLine("Put on a Jacket bro!"); } Console.Read(); } } }
So we now have made the query whether it is warmer or colder. So now go ahead and make this example as complex as you like. B.t.w. you can also use if statements within if statements. And you can use && in order to combine two conditions, e.g. temperature > 23 && sunIsShining == true. We are going into that in later examples.