Conditions

Conditions and If Statements

Logical Operators

C# supports the usual logical operators from mathematics, You can use these conditions to perform different actions for different decisions:

  • Less than: a < b

  • Less than or equal to: a <= b

  • Greater than: a > b

  • Greater than or equal to: a >= b

  • Equal to: a == b

  • Not Equal to: a != b

Conditional Statements

C# has the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true

  • Use else to specify a block of code to be executed, if the same condition is false

  • Use else if to specify a new condition to test, if the first condition is false

  • Use switch to specify many alternative blocks of code to be executed

Syntax

if (condition) 
{
  // block of code to be executed if the condition is True
}
if (condition)
{
  // block of code to be executed if the condition is True
} 
else 
{
  // block of code to be executed if the condition is False
}
if (condition1)
{
  // block of code to be executed if condition1 is True
} 
else if (condition2) 
{
  // block of code to be executed if the condition1 is false and condition2 is True
} 
else
{
  // block of code to be executed if the condition1 is false and condition2 is False
}

Exercise

Expectation

Read two numbers from user and print the one which is greater

Examples:

2
9
9
8
2
8
using System;

class Program
{
    static void Main()
    {       
        int a = Convert.ToInt32(Console.ReadLine()); 
        //todo - your code here                  
    }
}

Exercise

Expectations:

Print given message based on the age of the user:

Age < 18 → You cannot vote yet!

Age < 25 → Your vote is the future of the country!

Age < 60 → Your vote is important for country!

Otherwise → Your experience is vital for country!

Example:

Enter your age
24
Your vote is the furure of the country!
Have a good day!
using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your age");
        int age = Convert.ToInt32(Console.ReadLine());
        
        //todo - your code here
        
        /*you can cut-paste these to save time:        
        Console.WriteLine("You cannot vote yet!");
        Console.WriteLine("Your vote is the furure of the country!");
        Console.WriteLine("Your vote is important for country!");
        Console.WriteLine("Your experince is vital for country!");        
        Console.WriteLine("Have a good day!");
        */
    }
}

Last updated