Home C# Relational operators in C# tutorial

Relational operators in C# tutorial

Relational operators in C# are used to compare two values or expressions.

They return a boolean result (true or false) based on whether the comparison is true.

These operators are often used in conditional statements, like if or while, to control the flow of a program.

In this tutorial, we’ll cover:

1. Overview of Relational Operators

Here is a list of relational operators in C#:

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Each operator compares two values and returns true if the condition is met, otherwise false.

2. Examples with if Statements

Relational operators are commonly used in if statements to make decisions in your code.

Example 1: Checking Equality

using System;

public class EqualityExample
{
    public static void Main()
    {
        int a = 10;
        int b = 20;

        if (a == b)
        {
            Console.WriteLine("a is equal to b");
        }
        else
        {
            Console.WriteLine("a is not equal to b");
        }
    }
}

In this example:

  • The condition a == b checks if a is equal to b.
  • Since a is 10 and b is 20, the result is false, so it prints “a is not equal to b.”

Example 2: Checking Greater or Less Than

using System;

public class GreaterLessExample
{
    public static void Main()
    {
        int score = 85;

        if (score >= 90)
        {
            Console.WriteLine("Grade: A");
        }
        else if (score >= 80)
        {
            Console.WriteLine("Grade: B");
        }
        else
        {
            Console.WriteLine("Grade: C or lower");
        }
    }
}

In this example:

  • The program checks if score is greater than or equal to 90, then 80, assigning grades based on those conditions.
  • Since score is 85, it prints “Grade: B.”

3. Combining Relational Operators with Logical Operators

Relational operators can be combined with logical operators (&& for AND, || for OR) to create more complex conditions.

Example: Age and Citizenship Check

using System;

public class EligibilityCheck
{
    public static void Main()
    {
        int age = 20;
        bool isCitizen = true;

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

Here:

  • age >= 18 && isCitizen checks that both conditions are true.
  • Since age is 20 and isCitizen is true, the program outputs “You are eligible to vote.”

Example: Admission Eligibility

using System;

public class AdmissionEligibility
{
    public static void Main()
    {
        double grade = 85.0;
        int extracurricularActivities = 2;

        if (grade > 80 || extracurricularActivities >= 3)
        {
            Console.WriteLine("You are eligible for admission.");
        }
        else
        {
            Console.WriteLine("You are not eligible for admission.");
        }
    }
}

In this example:

  • grade > 80 || extracurricularActivities >= 3 checks if either the grade is high or there are enough extracurriculars.
  • Since grade is 85, it satisfies the condition and prints “You are eligible for admission.”

4. Using Relational Operators in Loops

Relational operators are also used in loops to control iteration based on conditions.

Example: Loop Until a Condition is Met

using System;

public class LoopExample
{
    public static void Main()
    {
        int number = 1;

        while (number <= 5)
        {
            Console.WriteLine("Number: " + number);
            number++;
        }
    }
}

In this example:

  • number <= 5 checks if number is less than or equal to 5.
  • The loop continues printing until number exceeds 5.

Example: Counting Down with for Loop

using System;

public class CountdownExample
{
    public static void Main()
    {
        for (int i = 10; i >= 1; i--)
        {
            Console.WriteLine("Countdown: " + i);
        }
    }
}

Here:

  • The loop uses i >= 1 as the condition, so it continues as long as i is greater than or equal to 1.
  • This produces a countdown from 10 to 1.

Practical Examples of Relational Operators

Example 1: Comparing User Input Values

using System;

public class ComparisonExample
{
    public static void Main()
    {
        Console.Write("Enter the first number: ");
        int num1 = int.Parse(Console.ReadLine());

        Console.Write("Enter the second number: ");
        int num2 = int.Parse(Console.ReadLine());

        if (num1 > num2)
        {
            Console.WriteLine("The first number is greater.");
        }
        else if (num1 < num2)
        {
            Console.WriteLine("The second number is greater.");
        }
        else
        {
            Console.WriteLine("Both numbers are equal.");
        }
    }
}

In this example:

  • The program takes two numbers as input and compares them using >, <, and ==.
  • It outputs whether the first number is greater, the second is greater, or if they’re equal.

Example 2: Checking Passing Grades

using System;

public class GradeCheck
{
    public static void Main()
    {
        Console.Write("Enter your grade: ");
        double grade = double.Parse(Console.ReadLine());

        if (grade >= 90)
        {
            Console.WriteLine("Grade: A");
        }
        else if (grade >= 80)
        {
            Console.WriteLine("Grade: B");
        }
        else if (grade >= 70)
        {
            Console.WriteLine("Grade: C");
        }
        else if (grade >= 60)
        {
            Console.WriteLine("Grade: D");
        }
        else
        {
            Console.WriteLine("Grade: F");
        }
    }
}

This example:

  • The program checks the grade and assigns letter grades based on ranges, using relational operators to set each range.
  • The code follows a descending order of conditions to ensure that the highest condition is checked first.

Summary

Relational operators in C# are essential for comparing values and making decisions based on those comparisons.

Here’s a recap:

  • Relational Operators: ==, !=, >, <, >=, and <= help compare two values.
  • Using in Conditions: They are often used with if statements for decision-making.
  • Combining with Logical Operators: You can use logical operators like && and || to combine conditions.
  • Loop Control: Relational operators are commonly used in loops to define the start, end, or exit conditions of the loop.

You may also like