C# Keywords Tutorial Part 26: else

C# Keywords Tutorial Part 26: else

The “else” keyword in C# is employed in conditional statements to furnish an alternate code block for execution in the event that the condition specified in the “if” statement is false. This blog post delves into the “else” keyword in greater depth and presents several code examples to illustrate its usage.

The fundamental syntax for implementing the “else” keyword in C# is outlined below:

if (condition)
{
   // Code to execute if the condition is true
}
else
{
   // Code to execute if the condition is false
}

In this code, the “if” statement is followed by a set of parentheses containing a condition to be evaluated. If the condition is true, the code block immediately following the “if” statement is executed. If the condition is false, the code block immediately following the “else” keyword is executed instead.

Code Examples Let’s look at some examples of how the “else” keyword can be used in C# code.

Example 1: Checking for even numbers

int num = 5;

if (num % 2 == 0)
{
   Console.WriteLine("The number is even");
}
else
{
   Console.WriteLine("The number is odd");
}

This piece of code initiates an integer variable “num” to 5. An “if” statement is used to examine if the remainder of “num” divided by 2 is equivalent to 0, signifying that “num” is an even number. In case the condition is valid, the message “The number is even” is displayed on the console. If the condition is untrue, however, the message “The number is odd” is printed instead.

Example 2: Validating user input

int age;

Console.Write("Please enter your age: ");
age = int.Parse(Console.ReadLine());

if (age >= 18)
{
   Console.WriteLine("You are old enough to vote");
}
else
{
   Console.WriteLine("You are not old enough to vote");
}

This code requests the user to enter their age and stores their input in an integer variable “age”. Following this, an “if” statement is utilized to evaluate if the value of “age” is greater than or equal to 18, which is the minimum voting age in various nations. When the condition is met, the message “You are old enough to vote” is exhibited on the console. Conversely, if the condition is false, the message “You are not old enough to vote” is printed instead.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *