05. Control Flow in C#
Level: Beginner
- What control flow means
- Use
iffor one condition - Use
if/elsefor two paths - Use
else iffor multiple decisions - Use
switchfor 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:
| Tool | Use |
|---|---|
if | Run code only when condition is true |
else | Run code when if is false |
else if | Check another condition |
switch | Choose 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 -
ifinside anotherif - Break - Statement ending a switch case
- Default - What happens when no case matches
When to Use Each Control Flow in SMS
| Scenario | Use | Example |
|---|---|---|
| Pass/fail decision | if/else | marks >= 35 -> Pass : Fail |
| Grade calculation | if/else if | >= 90 A+, >= 80 A, >= 70 B |
| Fee eligibility | if/else if | Check paid -> check attendance -> check exam |
| Menu choice | switch | "1: Add Student", "2: View Students" |
| Quick result | ternary ?: | 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
Expected output:
=== Sahasra Academy ===
=== Student Result ===
Name: Sneha Patel
Percentage: 84.8
Grade: A
Result: Pass
Exam Status: Eligible for next class.
Quick Reference
| Need | Use |
|---|---|
| One condition | if |
| Two paths | if/else |
| Many ranges | if/else if/else |
| Menu option | switch |
| Default case | default |
| Simple one-line result | ternary ? : |
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:
- Change percentage to 72 (should print "Grade: B")
- Change hasPaidFees to false (should print "Not allowed - fees pending")
- Change hasAttendance to false (should print "Not allowed - attendance shortage")
- Change percentage to 28 (should print "Failed")
See how conditions decide output. Try different combinations.
See if/else and switch in action. Video coming soon. Subscribe to NexCoding YouTube for updates.
Best Practices
- Use braces
{ }even for one-lineif. - Check specific conditions before general conditions.
- Use
if/elsefor ranges. - Use
switchfor fixed menu/status values. - Keep conditions readable.
- Avoid deep nesting.
- Use ternary only for simple one-line results.
- Always add
defaultinswitch.
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
| Question | Answer |
|---|---|
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 |
Control flow decides which code runs based on conditions.
Example:
if (marks >= 35)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Fail");
}
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
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;
}
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
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");
}
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 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.