Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🧠 Introduction
A real-world program needs more than just logic—it needs the
ability to make decisions, repeat tasks, and handle errors
gracefully. This chapter explores control flow statements that allow
branching and looping, along with error handling techniques in C#.
🔄 1. Control Flow in C#
Control flow determines how and when different parts
of your code get executed. In C#, it includes:
✅ 2. Conditional Statements
🔹 if Statement
Executes code only if a condition is true.
int
age = 18;
if
(age >= 18)
{
Console.WriteLine("You are eligible to
vote.");
}
🔹 if-else Statement
Provides an alternate block if the condition is false.
if
(age < 18)
{
Console.WriteLine("Not
eligible.");
}
else
{
Console.WriteLine("Eligible.");
}
🔹 else if Ladder
Used for multiple conditions.
int
marks = 75;
if
(marks >= 90)
Console.WriteLine("Grade A");
else
if (marks >= 75)
Console.WriteLine("Grade B");
else
Console.WriteLine("Grade C");
🔹 switch Statement
Efficient for multiple discrete values.
int
day = 3;
switch
(day)
{
case 1:
Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday"); break;
default: Console.WriteLine("Invalid
Day"); break;
}
📋 Comparison Table –
Conditionals
Statement |
Use Case |
Fallthrough |
if |
Single condition |
No |
if-else |
Dual path |
No |
else-if |
Multiple conditions |
No |
switch |
Multiple
fixed values |
Yes (without
break) |
🔁 3. Looping Statements
Used for repeating code blocks.
🔹 for Loop
Used when the number of iterations is known.
for
(int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
🔹 while Loop
Executes while a condition is true.
int
i = 0;
while
(i < 5)
{
Console.WriteLine(i);
i++;
}
🔹 do-while Loop
Always executes at least once.
int
j = 0;
do
{
Console.WriteLine(j);
j++;
}
while (j < 5);
🔹 foreach Loop
Iterates over collections.
string[]
colors = { "Red", "Green", "Blue" };
foreach
(string color in colors)
{
Console.WriteLine(color);
}
📋 Comparison Table –
Loops
Loop Type |
Entry/Exit Check |
When to Use |
for |
Entry |
Known iteration count |
while |
Entry |
Unknown
count; pre-check |
do-while |
Exit |
At least once
execution |
foreach |
Entry |
Collections/arrays |
🚀 4. Jump Statements
🔹 break
Exits a loop or switch.
for
(int i = 1; i <= 5; i++)
{
if (i == 3)
break;
Console.WriteLine(i); // 1 2
}
🔹 continue
Skips to next iteration.
for
(int i = 1; i <= 5; i++)
{
if (i == 3)
continue;
Console.WriteLine(i); // 1 2 4 5
}
🔹 return
Exits the method and optionally returns a value.
int
GetNumber()
{
return 42;
}
🔹 goto (use with caution)
Used to jump to a labeled statement.
int
i = 0;
start:
if
(i < 3)
{
Console.WriteLine(i++);
goto start;
}
⚠️ 5. Error Handling in C#
Errors are inevitable. Without proper handling, they can
crash your program. C# provides structured exception handling using:
✅ try-catch Block
try
{
int x = 5, y = 0;
Console.WriteLine(x / y); // Division by
zero!
}
catch
(DivideByZeroException e)
{
Console.WriteLine("Error: " +
e.Message);
}
✅ Multiple catch Blocks
try
{
int[] arr = { 1, 2 };
Console.WriteLine(arr[5]);
}
catch
(IndexOutOfRangeException e)
{
Console.WriteLine("Index out of range");
}
catch
(Exception ex)
{
Console.WriteLine("General
error");
}
✅ finally Block
Executes regardless of exception.
try
{
Console.WriteLine("Try block");
}
finally
{
Console.WriteLine("Always runs");
}
✅ throw Statement
Used to manually raise exceptions.
throw
new InvalidOperationException("Invalid operation");
📦 Common Exception Types
in C#
Exception Type |
When It Occurs |
DivideByZeroException |
Division by zero |
NullReferenceException |
Accessing
members on null objects |
IndexOutOfRangeException |
Array or list index
invalid |
FormatException |
Invalid data
type conversions |
InvalidOperationException |
Operation not valid in
current state |
IOException |
File or I/O
errors |
🧪 Sample Program: Error
Handling Example
using
System;
class
Program
{
static void Main()
{
try
{
Console.Write("Enter a number:
");
int num =
Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Reciprocal:
" + (1.0 / num));
}
catch (DivideByZeroException)
{
Console.WriteLine("Cannot
divide by zero.");
}
catch (FormatException)
{
Console.WriteLine("Invalid
input.");
}
finally
{
Console.WriteLine("Execution
completed.");
}
}
}
🧠 Best Practices for
Control Flow and Error Handling
📋 Summary Table
Concept |
Use |
if, else, switch |
Decision making |
for, while, do-while, foreach |
Looping |
break, continue,
return, goto |
Jumping in logic |
try, catch, finally, throw |
Structured
error handling |
A: Yes, especially with Visual Studio and .NET’s extensive documentation and community support.
A: Not at all. C# is independent and designed for new learners.
A: Yes, using ASP.NET Core you can build scalable web apps and APIs.
A: Both are similar syntactically, but C# is part of the Microsoft .NET ecosystem and often integrates better with Windows technologies.
A: Not anymore. With .NET Core and .NET 8, C# is cross-platform.
A: Absolutely. It is the main language used in Unity.
A: Visual Studio is the most powerful and popular IDE for C# development.
A: Yes, with Xamarin or .NET MAUI, C# can build cross-platform mobile apps.
A: C# continues to evolve with modern features and has strong backing from Microsoft, making it future-proof.
A: No, you can code, compile, and run C# locally, though some online libraries/tools may require internet.
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)