Skip to main content

05. Control Flow in C#

Level: Beginner

ℹ️ What You'll Learn
  • What control flow means
  • Use if for one condition
  • Use if/else for two paths
  • Use else if for multiple decisions
  • Use switch for menu/status choices
  • Use simple ternary decisions
  • Build a student grade and eligibility checker

In the previous article, you learned operators.

Operators help calculate and compare values.

Control flow helps the program decide which code should run.

Example:

if (marks >= 35)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}

The Problem: How Does Code Make Decisions?

In a School Management System, the app must decide:

  • Did the student pass or fail?
  • Which grade should be given?
  • Is the student allowed to write the exam?
  • Is fee payment complete or pending?
  • Which menu option did the user choose?

These decisions use control flow.

What is Control Flow?

Control flow means deciding the path of execution.

Condition is true -> run this code
Condition is false -> run another code

Common control flow tools:

ToolUse
ifRun code only when condition is true
elseRun code when if is false
else ifCheck another condition
switchChoose from many fixed options
ternary ? :Simple one-line decision

Quick Definitions

  • Control Flow - Deciding which code runs based on conditions
  • Condition - Statement that is true or false
  • Branch - Different path code can take
  • Nested - if inside another if
  • Break - Statement ending a switch case
  • Default - What happens when no case matches

When to Use Each Control Flow in SMS

ScenarioUseExample
Pass/fail decisionif/elsemarks >= 35 -> Pass : Fail
Grade calculationif/else if>= 90 A+, >= 80 A, >= 70 B
Fee eligibilityif/else ifCheck paid -> check attendance -> check exam
Menu choiceswitch"1: Add Student", "2: View Students"
Quick resultternary ?:marks >= 35 ? "Pass" : "Fail"

Step 1: if Statement

Use if when you want to run code only if a condition is true.

int marks = 82;

if (marks >= 35)
{
Console.WriteLine("Student passed.");
}

Output:

Student passed.

If marks are below 35, nothing prints.

Step 2: if/else Statement

Use if/else when there are two paths.

int marks = 28;

if (marks >= 35)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}

Output:

Fail

Step 3: else if for Multiple Conditions

Use else if when there are many possible results.

Example: grade calculation.

double percentage = 84.5;

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

Output:

Grade: A

Important: Order Matters

The first matching condition runs. Rest are skipped.

Wrong Order (Problem)

int marks = 85;

if (marks >= 35) // 85 >= 35? YES
{
Console.WriteLine("Pass"); // Runs this
}
else if (marks >= 80) // Never checked (already matched above)
{
Console.WriteLine("Grade A");
}

Output: Pass (Wrong! Should be "Grade A")

Correct Order (Solution)

if (marks >= 80) // 85 >= 80? YES
{
Console.WriteLine("Grade A"); // Runs this
}
else if (marks >= 35) // Skipped (already matched)
{
Console.WriteLine("Pass");
}

Output: Grade A (Correct!)

Visual Flow Diagram

WRONG ORDER:
marks = 85
1. Check marks >= 35 -> true, prints "Pass"
2. marks >= 80 is never checked

CORRECT ORDER:
marks = 85
1. Check marks >= 80 -> true, prints "Grade A"
2. marks >= 35 is skipped

Beginner rule: For ranges, check highest condition first.

For grade calculation:

// Check from highest to lowest
if (percentage >= 90) // A+
else if (percentage >= 80) // A
else if (percentage >= 70) // B
else if (percentage >= 60) // C
else if (percentage >= 35) // D
else // F

Step 4: Combine Conditions

Use && when all conditions must be true.

bool hasPaidFees = true;
bool hasAttendance = true;

if (hasPaidFees && hasAttendance)
{
Console.WriteLine("Eligible for exam.");
}
else
{
Console.WriteLine("Not eligible for exam.");
}

Use || when any one condition can be true.

bool isTeacher = false;
bool isAdmin = true;

if (isTeacher || isAdmin)
{
Console.WriteLine("Access allowed.");
}

Use ! to reverse a condition.

bool hasPaidFees = false;

if (!hasPaidFees)
{
Console.WriteLine("Fees pending.");
}

Step 5: Avoid Deep Nested if

Nested if means if inside another if.

Wrong: Deep Nesting (Hard to Read)

if (hasPaidFees)
{
if (hasAttendance)
{
if (marks >= 35)
{
Console.WriteLine("Eligible");
}
}
}

Problem: Hard to follow. Lots of indentation. What if fees NOT paid? Code doesn't say.

Correct: Flat Structure (Easy to Read)

if (!hasPaidFees)
{
Console.WriteLine("Not eligible - fees pending.");
}
else if (!hasAttendance)
{
Console.WriteLine("Not eligible - attendance shortage.");
}
else if (marks < 35)
{
Console.WriteLine("Not eligible - failed exam.");
}
else
{
Console.WriteLine("Eligible.");
}

Better: Clear. All paths shown. Easy to understand.

Visual Comparison

Nested version:
if paid -> if attendance -> if marks >= 35 -> Eligible

Flat version:
if not paid -> Not eligible
else if no attendance -> Not eligible
else if marks < 35 -> Not eligible
else -> Eligible

Beginner rule: Use else if to keep code flat and readable.

Step 6: switch Statement

Use switch when checking one value against many fixed options.

Example: menu choice.

int choice = 2;

switch (choice)
{
case 1:
Console.WriteLine("Add Student");
break;

case 2:
Console.WriteLine("View Students");
break;

case 3:
Console.WriteLine("Exit");
break;

default:
Console.WriteLine("Invalid choice");
break;
}

Output:

View Students

Use switch for:

  • Menu options
  • Status values
  • Fixed codes
  • Exact matches

Use if/else for:

  • Marks ranges
  • Fees comparison
  • Attendance conditions
  • Multiple combined checks

Step 7: switch with Student Status

string status = "Active";

switch (status)
{
case "Active":
Console.WriteLine("Student can attend classes.");
break;

case "Inactive":
Console.WriteLine("Student cannot attend classes.");
break;

case "Transferred":
Console.WriteLine("Student moved to another school.");
break;

default:
Console.WriteLine("Unknown student status.");
break;
}

Remember:

Each case should end with break.
default runs when no case matches.

Step 8: Ternary Operator for Simple Decisions

You already saw ternary in the operators article.

Use it only for simple one-line decisions.

int marks = 82;

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

Console.WriteLine(result);

Do not use ternary for complex grade logic while learning. Use if/else.

Full Example: Student Result and Eligibility

💻 Try It — Console App
💡 Paste into Program.cs and press F5⌥ GitHub
string studentName = "Sneha Patel";
string schoolName = "Sahasra Academy";
double percentage = 84.8;
bool hasPaidFees = true;
bool hasAttendance = true;

string grade;

if (percentage >= 90)
{
grade = "A+";
}
else if (percentage >= 80)
{
grade = "A";
}
else if (percentage >= 70)
{
grade = "B";
}
else if (percentage >= 60)
{
grade = "C";
}
else if (percentage >= 35)
{
grade = "D";
}
else
{
grade = "F";
}

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

Console.WriteLine($"=== {schoolName} ===");
Console.WriteLine("=== Student Result ===");
Console.WriteLine($"Name: {studentName}");
Console.WriteLine($"Percentage: {percentage}");
Console.WriteLine($"Grade: {grade}");
Console.WriteLine($"Result: {result}");

if (!hasPaidFees)
{
Console.WriteLine("Exam Status: Not allowed - fees pending.");
}
else if (!hasAttendance)
{
Console.WriteLine("Exam Status: Not allowed - attendance shortage.");
}
else if (percentage < 35)
{
Console.WriteLine("Exam Status: Failed.");
}
else
{
Console.WriteLine("Exam Status: Eligible for next class.");
}

Expected output:

=== Sahasra Academy ===
=== Student Result ===
Name: Sneha Patel
Percentage: 84.8
Grade: A
Result: Pass
Exam Status: Eligible for next class.

Quick Reference

NeedUse
One conditionif
Two pathsif/else
Many rangesif/else if/else
Menu optionswitch
Default casedefault
Simple one-line resultternary ? :

When You'll Use This in SMS

Control flow is the decision engine of SMS.

Student eligibility:

if (!hasPaidFees)
-> "Not eligible - fees pending"
else if (!hasAttendance)
-> "Not eligible - attendance shortage"
else if (percentage < 35)
-> "Not eligible - failed exam"
else
-> "Eligible for next class"

Grade calculation:

if (percentage >= 90) -> Grade A+
else if (percentage >= 80) -> Grade A
else if (percentage >= 70) -> Grade B
else if (percentage >= 60) -> Grade C
else if (percentage >= 35) -> Grade D
else -> Grade F

Menu choice:

switch (choice)
case 1 -> Add Student
case 2 -> View Students
case 3 -> Exit
default -> Invalid

Real impact:

  • Wrong logic = wrong decisions
  • SMS tells passing student they failed = system fails
  • Order of conditions matters = design matters

Common Mistakes (3 Critical)

Mistake 1: Using = instead of ==

Wrong:

if (marks = 100)
{
}

Correct:

if (marks == 100)
{
}

Mistake 2: Wrong condition order

Wrong:

if (percentage >= 35)
{
Console.WriteLine("Pass");
}
else if (percentage >= 90)
{
Console.WriteLine("A+");
}

Problem: 90 >= 35 is true, first condition matches. A+ never runs.

Correct:

if (percentage >= 90)
{
Console.WriteLine("A+");
}
else if (percentage >= 35)
{
Console.WriteLine("Pass");
}

Mistake 3: Forgetting braces

Wrong:

if (percentage >= 35)
Console.WriteLine("Pass");
Console.WriteLine("Eligible");

Only first line belongs to if. Second line always runs.

Correct:

if (percentage >= 35)
{
Console.WriteLine("Pass");
Console.WriteLine("Eligible");
}

Try This Now

Run the student result and eligibility example above. Then experiment:

  1. Change percentage to 72 (should print "Grade: B")
  2. Change hasPaidFees to false (should print "Not allowed - fees pending")
  3. Change hasAttendance to false (should print "Not allowed - attendance shortage")
  4. Change percentage to 28 (should print "Failed")

See how conditions decide output. Try different combinations.


ℹ️ Video Tutorial

See if/else and switch in action. Video coming soon. Subscribe to NexCoding YouTube for updates.


Best Practices

  1. Use braces { } even for one-line if.
  2. Check specific conditions before general conditions.
  3. Use if/else for ranges.
  4. Use switch for fixed menu/status values.
  5. Keep conditions readable.
  6. Avoid deep nesting.
  7. Use ternary only for simple one-line results.
  8. Always add default in switch.

Practice Task

Create a program that checks fee status.

Data:

Student Name: Priya Sharma
Total Fees: 40000
Paid Amount: 40000
Attendance: 82
Percentage: 76

Rules:

  • If paid amount is less than total fees, print Fees Pending.
  • Else if attendance is less than 75, print Attendance Shortage.
  • Else if percentage is less than 35, print Failed.
  • Else print Eligible for next class.

Starter:

string studentName = "Priya Sharma";
decimal totalFees = 40000.00m;
decimal paidAmount = 40000.00m;
double attendance = 82;
double percentage = 76;

Console.WriteLine($"Student: {studentName}");

if (paidAmount < totalFees)
{
Console.WriteLine("Fees Pending");
}
else if (attendance < 75)
{
Console.WriteLine("Attendance Shortage");
}
else if (percentage < 35)
{
Console.WriteLine("Failed");
}
else
{
Console.WriteLine("Eligible for next class");
}

Quick Revision

QuestionAnswer
What does if do?Runs code when condition is true
What does else do?Runs when if is false
When to use else if?Multiple conditions
When to use switch?Fixed menu/status choices
What does default do?Runs when no switch case matches
Why use braces?To clearly group statements

🎯 Q1: What is control flow in C#?

Control flow decides which code runs based on conditions.

Example:

if (marks >= 35)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}
🎯 Q2: When should we use if/else?

Use if/else when you need to check conditions like ranges or combined rules.

Examples:

  • Marks >= 35
  • Attendance >= 75
  • Fees paid or pending
  • Percentage ranges for grades
🎯 Q3: When should we use switch?

Use switch when one value can match many fixed options.

Example:

switch (choice)
{
case 1:
Console.WriteLine("Add Student");
break;
case 2:
Console.WriteLine("View Students");
break;
default:
Console.WriteLine("Invalid choice");
break;
}
🎯 Q4: What is the difference between if/else and switch?

if/else is better for ranges and complex conditions.

switch is better for exact values like menu options, status, or codes.

Example:

Marks >= 90 -> if/else
Choice == 1/2/3 -> switch
🎯 Q5: Why does condition order matter?

The first matching condition runs and the rest are skipped.

For grade calculation, check higher marks first:

if (percentage >= 90)
{
Console.WriteLine("A+");
}
else if (percentage >= 80)
{
Console.WriteLine("A");
}
🎯 Q6: What is the ternary operator?

The ternary operator is a short form of simple if/else.

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

Use it only for simple one-line decisions.


🤖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# control flow and conditions. Try these prompts:

  • "Explain if, else if, else, and switch using school examples"
  • "Give me 10 practice questions for C# control flow"
  • "Explain when to use switch instead of if/else"
  • "Quiz me with 5 beginner questions about control flow"

💡 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

Loops in C# ->

nexcoding.in