Booleans
Booleans are a primitive data type in C# that represents a logical value, either true or false. They are used to express conditions and make decisions in the program's execution.
Declaring and Initializing Boolean Variables
Boolean variables are declared using the bool keyword. They can be initialized with either true or false values. For example:
bool isStudent = true;
bool isAdult = false;
Boolean Expressions
Boolean expressions involve comparisons or logical operations that result in a boolean value. Comparison operators like ==, !=, <, <=, >, and >= compare two values and return true or false based on the comparison result. Logical operators like && (logical AND), || (logical OR), and ! (logical NOT) combine boolean values and produce a new boolean value.
Example:
int age = 25;
bool isMajorOfAge = (age >= 18); // isMajorOfAge = true
Conditional Statements
Conditional statements, such as if, else, and switch, use boolean expressions to control the flow of program execution. They execute specific code blocks based on the truth value of the condition.
Example:
int score = 85;
if (score >= 90) {
Console.WriteLine("Excellent!");
} else if (score >= 80) {
Console.WriteLine("Great!");
} else if (score >= 70) {
Console.WriteLine("Good!");
} else {
Console.WriteLine("Try harder next time.");
}
Boolean Variables in Methods
Boolean values can be returned from methods and passed as arguments to methods. This allows for modular code that encapsulates logic and promotes code reuse.
Example:
bool isEven(int number) {
return (number % 2 == 0);
}
int inputNumber = 10;
if (isEven(inputNumber)) {
Console.WriteLine($"{inputNumber} is even.");
} else {
Console.WriteLine($"{inputNumber} is odd.");
}
Conclusion
Booleans are fundamental building blocks of C# programming, enabling conditional statements, logical operations, and decision-making logic. They provide a concise and powerful way to express conditions and control the program's flow of execution.