Skip to main content

04. Operators and Expressions in C#

Level: Beginner

ℹ️ What You'll Learn
  • What operators are
  • Calculate total marks and percentage
  • Compare marks to decide pass or fail
  • Use logical operators for eligibility checks
  • Update values using assignment operators
  • Use ternary operator for simple results
  • Avoid common operator mistakes

In the previous article, you learned variables.

Variables store data. Operators help us work with that data.

Example:

int total = maths + science;
bool hasPassed = percentage >= 35;

Here:

  • + adds values
  • >= compares values

These symbols are called operators.

The Problem: How Do We Calculate Student Results?

In a School Management System, we need to calculate:

  • Total marks
  • Percentage
  • Pass or fail
  • Fee balance
  • Exam eligibility

Example:

Maths: 90
Science: 80
English: 70

Total = 240
Percentage = 80
Result = Pass

Operators help us do these calculations.

What is an Operator?

An operator is a symbol that performs an action.

int total = 90 + 80;
PartMeaning
90First value
+Operator
80Second value
totalVariable storing result

Common Operator Types

TypeOperatorsUse
Arithmetic+, -, *, /, %Calculations
Comparison==, !=, >, <, >=, <=Check values
Logical&&, `
Assignment=, +=, -=, *=, /=Store/update values
Ternary? :Simple if/else in one line
Null-safe??, ?.Handle missing values safely

Quick Definitions

  • Operator - Symbol that performs an action on values
  • Arithmetic - Operators for calculations (+, -, *, /)
  • Comparison - Operators for checking values (>, ==, !=)
  • Logical - Operators for combining conditions (&&, ||, !)
  • Assignment - Operators for storing or updating values (=, +=, -=)
  • Type Casting - Converting one data type to another
  • Operator Precedence - Order in which operations happen

Important: Integer Division

When you divide two integers, C# drops the decimal part.

int result = 10 / 3; // 3 (not 3.333)
double result2 = 10.0 / 3; // 3.333 (decimal numbers)

This matters for marks and fees calculations.

Use double when you need accurate decimal results.

For percentage from integers:

int total = 424;

// Wrong: both are integers
double percentage = total / 500 * 100; // gives 0

// Correct: convert to double first
double percentage = (double)total / 500 * 100; // gives 84.8

Step 1: Arithmetic Operators

Arithmetic operators are used for calculations.

OperatorMeaningExample
+Add10 + 5
-Subtract10 - 5
*Multiply10 * 5
/Divide10 / 5
%Remainder10 % 3

Example:

int maths = 90;
int science = 80;
int english = 70;

int total = maths + science + english;
double percentage = (double)total / 300 * 100;

Console.WriteLine($"Total: {total}");
Console.WriteLine($"Percentage: {percentage}");

Why (double) Casting is Needed

Problem: If both numbers are integers, the result is an integer (decimal part lost).

int total = 424;
int maxMarks = 500;

// Wrong: both integers, 424 / 500 = 0 (integer division)
double percentage = total / maxMarks * 100; // gives 0

// Correct: convert total to double first
double percentage = (double)total / maxMarks * 100; // gives 84.8

Beginner rule: For percentage or average from integers, use (double) casting on the first number.

This tells C#: "Treat this as a decimal number, not an integer."

Another way (also correct):

double percentage = total / 500.0 * 100; // 500.0 is double

Step 2: Fee Calculation

Use decimal for money.

decimal totalFees = 30000.00m;
decimal paidAmount = 18000.00m;
decimal balance = totalFees - paidAmount;

Console.WriteLine($"Balance Fees: {balance}");

Output:

Balance Fees: 12000.00

Step 3: Comparison Operators

Comparison operators return true or false.

OperatorMeaningExample
==Equal tomarks == 100
!=Not equal tomarks != 0
>Greater thanmarks > 35
<Less thanmarks < 35
>=Greater than or equalmarks >= 35
<=Less than or equalmarks <= 100

Example:

double percentage = 80;

bool hasPassed = percentage >= 35;
bool hasDistinction = percentage >= 75;
bool isFullMarks = percentage == 100;

Console.WriteLine($"Passed: {hasPassed}");
Console.WriteLine($"Distinction: {hasDistinction}");
Console.WriteLine($"Full Marks: {isFullMarks}");

Step 4: Logical Operators

Logical operators combine multiple true or false values.

OperatorMeaningExample
&&AND - both must be truehasPaidFees && hasAttendance
``
!NOT - reverse value!hasPaidFees

Example:

bool hasPaidFees = true;
bool hasAttendance = true;
bool hasPassedExam = false;

bool canWriteExam = hasPaidFees && hasAttendance;
bool canGetCertificate = hasPaidFees && hasAttendance && hasPassedExam;
bool isBlocked = !hasPaidFees;

Console.WriteLine($"Can write exam: {canWriteExam}");
Console.WriteLine($"Can get certificate: {canGetCertificate}");
Console.WriteLine($"Blocked: {isBlocked}");

Step 5: Assignment Operators

Assignment means storing or updating a value.

OperatorMeaningSame As
=Assignx = 10
+=Add and assignx = x + 5
-=Subtract and assignx = x - 5
*=Multiply and assignx = x * 2
/=Divide and assignx = x / 2

Example:

decimal balance = 30000.00m;

balance -= 10000.00m; // paid 10000
balance += 500.00m; // late fee added

Console.WriteLine($"Final Balance: {balance}");

Step 6: Increment and Decrement

Use ++ to add 1.

Use -- to subtract 1.

int presentDays = 20;

presentDays++;
Console.WriteLine(presentDays); // 21

presentDays--;
Console.WriteLine(presentDays); // 20

Use this later in loops and counters.

Step 7: Ternary Operator

Ternary operator is a short way to write simple if/else.

Syntax:

condition ? valueIfTrue : valueIfFalse

Example:

double percentage = 80;

string result = percentage >= 35 ? "Pass" : "Fail";

Console.WriteLine(result);

Use ternary only for simple decisions.

For complex logic, use if/else in the next article.

Step 8: Null-Safe Operators

ℹ️ Skip This Section For Later

Operators ?? (null coalescing) and ?. (null-conditional) handle missing data.

You'll learn about null values in detail in Article 23: Nullable Types.

For now, focus on arithmetic, comparison, and logical operators. Come back to this section after you understand null values.

Full Example: Student Result Calculator

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
string studentName = "Arjun Reddy";
string schoolName = "Sahasra Academy";

int english = 82;
int maths = 91;
int science = 78;
int social = 85;
int language = 88;

int totalMarks = english + maths + science + social + language;
double percentage = (double)totalMarks / 500 * 100;

bool hasPassed = percentage >= 35;
bool hasDistinction = percentage >= 75;

string result = hasPassed ? "Pass" : "Fail";
string distinction = hasDistinction ? "Yes" : "No";

decimal totalFees = 30000.00m;
decimal paidAmount = 20000.00m;
decimal balanceFees = totalFees - paidAmount;

Console.WriteLine($"=== {schoolName} ===");
Console.WriteLine("=== Student Result ===");
Console.WriteLine($"Name: {studentName}");
Console.WriteLine($"Total Marks: {totalMarks}/500");
Console.WriteLine($"Percentage: {percentage:F2}");
Console.WriteLine($"Result: {result}");
Console.WriteLine($"Distinction: {distinction}");
Console.WriteLine($"Balance Fees: {balanceFees}");

Expected output:

=== Sahasra Academy ===
=== Student Result ===
Name: Arjun Reddy
Total Marks: 424/500
Percentage: 84.80
Result: Pass
Distinction: Yes
Balance Fees: 10000.00

Operator Precedence (Order Matters)

Operator precedence means: some operators run before others.

Example:

int result = 10 + 5 * 3;

Question: Is the answer 45 or 25?

10 + 5 = 15, then 15 * 3 = 45 // Wrong
10 + (5 * 3) = 10 + 15 = 25 // Correct

Why? Multiplication happens before addition.

To force different order, use parentheses:

int result1 = 10 + 5 * 3; // 25 (multiply first)
int result2 = (10 + 5) * 3; // 45 (parentheses first)

Beginner rule: When in doubt, use parentheses. It makes code clear.

For marks and fees:

double percentage = (double)total / maxMarks * 100;

// Parentheses make it clear:
// 1. Convert total to double
// 2. Divide by maxMarks
// 3. Multiply by 100

Quick Reference

NeedExample
Add markstotal = maths + science
Calculate balancebalance = totalFees - paidAmount
Check passpercentage >= 35
Check both conditionshasPaidFees && hasAttendance
Check either condition`isTeacher
Reverse condition!hasPaidFees
Add late feebalance += 500
Simple result textmarks >= 35 ? "Pass" : "Fail"
Default for null laterphone ?? "Not Provided"

When You'll Use This in SMS

Operators are core to SMS calculations.

Student marks calculation:

  • Total: english + maths + science + social + language
  • Percentage: (double)totalMarks / 500 * 100
  • Pass/Fail: percentage >= 35

Fee calculation:

  • Balance: totalFees - paidAmount
  • With late fee: balance += 500
  • Fully paid: balance == 0

Eligibility check:

  • Can write exam: hasPaidFees && hasAttendance
  • Can get certificate: hasPaidFees && hasAttendance && hasPassedExam

Real impact:

  • Wrong operators = wrong calculations
  • Wrong data types = lost money (use decimal)
  • Right operators = reliable SMS for thousands of students

Common Mistakes (3 Critical)

Mistake 1: Using = instead of ==

Wrong:

if (marks = 100)
{
}

Correct:

if (marks == 100)
{
}

Meaning:

= assigns value
== compares value

Mistake 2: Integer division

Wrong:

int total = 424;
double percentage = total / 500 * 100;

Result: Wrong. Both are integers.

Correct:

double percentage = (double)total / 500 * 100;

Mistake 3: Forgetting parentheses

Wrong:

int result = 10 + 5 * 3; // 25, not 45

Correct if you want 45:

int result = (10 + 5) * 3;

Try This Now

Run the result calculator example above. Then experiment:

  1. Change marks values: english=90, maths=92, science=88, social=86, language=89
  2. Run and see new percentage
  3. Change balanceFees values: what if paid amount is 25000 instead of 20000?
  4. Change totalFees: what if fees were Rs. 40000 instead of Rs. 30000?

See how operators calculate different results based on input values.


ℹ️ Video Tutorial

C# operators video coming soon on NexCoding YouTube. Subscribe for updates.


Best Practices

  1. Use parentheses for clear calculations.
  2. Use decimal for money calculations.
  3. Use (double) when calculating percentage from integers.
  4. Use == for comparison, not =.
  5. Use && when all conditions must be true.
  6. Use || when any one condition can be true.
  7. Use ternary only for simple one-line decisions.

Practice Task

Create a program for fee calculation:

Student Name: Priya Sharma
Total Fees: 40000.00
Paid Amount: 25000.00
Late Fee: 500.00

Calculate:

  • Balance fees
  • Final balance after adding late fee
  • Whether payment is complete

Expected starter:

string studentName = "Priya Sharma";
decimal totalFees = 40000.00m;
decimal paidAmount = 25000.00m;
decimal lateFee = 500.00m;

decimal balance = totalFees - paidAmount;
balance += lateFee;

bool isFullyPaid = balance == 0;

Console.WriteLine($"Student: {studentName}");
Console.WriteLine($"Final Balance: {balance}");
Console.WriteLine($"Fully Paid: {isFullyPaid}");

Quick Revision

QuestionAnswer
Which operator adds values?+
Which operator compares equality?==
Which operator assigns value?=
Which operator means AND?&&
Which operator means OR?`
Which operator gives default for null later???
Which operator is used for simple if/else?? :

🎯 Q1: What is an operator in C#?

An operator is a symbol that performs an action on values.

Example:

int total = 50 + 40;
bool passed = total >= 35;

Here, + adds values and >= compares values.

🎯 Q2: What is the difference between = and ==?

= is assignment. It stores a value.

== is comparison. It checks whether two values are equal.

Example:

int marks = 100; // assignment
bool full = marks == 100; // comparison
🎯 Q3: What is integer division?

Integer division happens when both values are integers.

Example:

int result = 10 / 3; // 3

The decimal part is removed.

Use double when you need decimal result:

double result = 10.0 / 3;
🎯 Q4: What is the difference between && and ||?

&& means AND. All conditions must be true.

|| means OR. Any one condition can be true.

Example:

bool canWriteExam = hasPaidFees && hasAttendance;
bool canEnterCampus = isStudent || isTeacher;
🎯 Q5: What is the ternary operator?

The ternary operator is a short way to return one of two values based on a condition.

Example:

string result = marks >= 35 ? "Pass" : "Fail";

Use it only for simple conditions.

🎯 Q6: What is the null coalescing operator?

The null coalescing operator ?? gives a default value when the left side is null.

Example:

string? phone = null;
string display = phone ?? "Not Provided";

Here, display becomes "Not Provided".


🤖Use AI to Learn Faster
⚠️ Important for beginners: Do NOT use AI to write your code yet. Type every example yourself. Your brain learns by doing, not by reading AI output. Use AI only to explain and quiz you — not to code for you. Once you have strong fundamentals, AI becomes a powerful productivity tool for repetitive tasks.

Use ChatGPT, Claude, or Copilot to go deeper on C# operators. Try these prompts:

  • "Explain C# operators using student marks and fee examples"
  • "Give me 10 practice questions for arithmetic, comparison, and logical operators"
  • "Explain the difference between = and == with examples"
  • "Quiz me with 5 beginner questions about C# operators"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

Control Flow - if/else and switch ->

nexcoding.in