Introduction
Welcome to Module 2 of our Complete C# Course: From Beginner to Advanced! After mastering the basics of C# and the .NET ecosystem in Module 1, it’s time to add logic and interactivity to your programs with control flow and operators. In this module, we’ll cover arithmetic, relational, and logical operators, decision-making with if/else and switch statements, and iteration with for, while, do-while, and foreach loops, along with control statements like break, continue, and goto. We’ll apply these concepts in practical mini-programs, including a calculator, even/odd checker, and a number guessing game, all inspired by real-world scenarios. With detailed examples, best practices, and pros/cons, you’ll learn to create dynamic, user-driven applications. Let’s get started!
1. Arithmetic, Relational, and Logical Operators
Operators perform operations on variables and values, enabling calculations, comparisons, and logical decisions.
Arithmetic Operators
+ (addition), - (subtraction), * (multiplication), / (division), % (modulus).
++ (increment), -- (decrement).
Relational Operators
== (equal), != (not equal), <, >, <=, >=.
Logical Operators
&& (and), || (or), ! (not).
Example: Basic Operations
using System;
namespace OperatorDemo
{
class Program
{
static void Main(string[] args)
{
int a = 10, b = 3;
// Arithmetic
Console.WriteLine($"Sum: {a + b}"); // 13
Console.WriteLine($"Modulus: {a % b}"); // 1
Console.WriteLine($"Increment: {++a}"); // 11
// Relational
Console.WriteLine($"Is equal: {a == b}"); // False
Console.WriteLine($"Is greater: {a > b}"); // True
// Logical
bool isPositive = a > 0;
bool isEven = a % 2 == 0;
Console.WriteLine($"Positive and Even: {isPositive && isEven}"); // False
}
}
}
Real-World Use: Calculating totals in a shopping cart, comparing user inputs, or validating conditions in forms.
Pros:
Arithmetic operators handle common calculations efficiently.
Relational operators enable precise comparisons.
Logical operators combine conditions for complex logic.
Cons:
Division by zero causes exceptions (/, %).
Logical operator precedence can be confusing (e.g., && before ||).
Best Practices:
Use parentheses to clarify operator precedence (e.g., (a && b) || c).
Handle division by zero with checks.
Avoid overusing ++/-- in complex expressions for readability.
Alternatives:
Math library (Math.Pow, Math.Abs) for advanced calculations.
LINQ for complex logical conditions.
2. If, Else, and Switch Statements
Decision-making statements control program flow based on conditions.
If/Else
Executes code blocks based on boolean conditions.
Switch
Selects a code block based on a variable’s value.
Example: Grade Calculator
using System;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter your score (0-100): ");
if (!int.TryParse(Console.ReadLine(), out int score) || score < 0 || score > 100)
{
Console.WriteLine("Invalid score!");
return;
}
// If/Else
if (score >= 90)
Console.WriteLine("Grade: A");
else if (score >= 80)
Console.WriteLine("Grade: B");
else
Console.WriteLine("Grade: C or below");
// Switch (C# 8+ switch expression)
string grade = score switch
{
>= 90 => "A",
>= 80 => "B",
_ => "C or below"
};
Console.WriteLine($"Switch Grade: {grade}");
}
}
}
Real-World Use: Grading systems, user role checks, or form validation.
Pros:
if/else is flexible for complex conditions.
switch is concise for multiple discrete values.
C# 8+ switch expressions are expressive and functional.
Cons:
Nested if/else can become unreadable (if-else hell).
switch is limited to equality checks on constants.
Best Practices:
Use if/else for range-based or complex conditions.
Prefer switch expressions for cleaner code (C# 8+).
Avoid deep nesting; refactor into methods or use guard clauses.
Alternatives:
Pattern matching (C# 7+) for advanced switch cases.
Dictionary lookups for mapping values to actions.
3. Loops: For, While, Do-While, Foreach
Loops execute code repeatedly based on conditions or collections.
For Loop
Iterates a fixed number of times.
While Loop
Runs while a condition is true.
Do-While Loop
Runs at least once, then checks the condition.
Foreach Loop
Iterates over collections (e.g., arrays, lists).
Example: Shopping List Printer
using System;
using System.Collections.Generic;
namespace ShoppingList
{
class Program
{
static void Main(string[] args)
{
List<string> items = new List<string> { "Milk", "Bread", "Eggs" };
// For loop
Console.WriteLine("For Loop:");
for (int i = 0; i < items.Count; i++)
{
Console.WriteLine($"{i + 1}. {items[i]}");
}
// While loop
Console.WriteLine("\nWhile Loop:");
int index = 0;
while (index < items.Count)
{
Console.WriteLine($"{index + 1}. {items[index]}");
index++;
}
// Do-While loop
Console.WriteLine("\nDo-While Loop:");
index = 0;
do
{
Console.WriteLine($"{index + 1}. {items[index]}");
index++;
} while (index < items.Count);
// Foreach loop
Console.WriteLine("\nForeach Loop:");
foreach (var item in items)
{
Console.WriteLine($"- {item}");
}
}
}
}
Real-World Use: Iterating over order items, processing data batches, or generating reports.
Pros:
for: Precise control over iteration.
while: Flexible for dynamic conditions.
do-while: Guarantees at least one iteration.
foreach: Clean and safe for collections.
Cons:
for: Error-prone with index management.
while/do-while: Risk of infinite loops.
foreach: Limited to collections; no index access.
Best Practices:
Use foreach for simple collection iteration.
Ensure loop termination conditions to avoid infinite loops.
Use for when index is needed; while for condition-driven loops.
Alternatives:
LINQ for declarative iteration (e.g., items.ForEach()).
Recursion for specific scenarios (use cautiously).
4. Break, Continue, and Goto
Control statements alter loop or switch execution.
Break
Exits the loop or switch.
Continue
Skips to the next loop iteration.
Goto
Jumps to a labeled statement (use sparingly).
Example: Process Orders
using System;
namespace OrderProcessor
{
class Program
{
static void Main(string[] args)
{
int[] orders = { 100, 0, 200, -50, 300 };
for (int i = 0; i < orders.Length; i++)
{
if (orders[i] == 0)
{
Console.WriteLine("Skipping zero order");
continue; // Skip to next iteration
}
if (orders[i] < 0)
{
Console.WriteLine("Invalid order detected!");
break; // Exit loop
}
Console.WriteLine($"Processing order: ${orders[i]}");
if (i == orders.Length - 1)
{
goto Summary; // Jump to label
}
}
Summary:
Console.WriteLine("Order processing complete.");
}
}
}
Real-World Use: Skipping invalid data in a dataset or exiting on critical errors.
Pros:
break: Cleanly exits loops/switches.
continue: Simplifies skipping logic.
goto: Useful for complex control flow (rare).
Cons:
goto can make code hard to follow (spaghetti code).
Overusing break/continue reduces readability.
Best Practices:
Use break/continue for clear, simple control.
Avoid goto unless absolutely necessary; prefer methods or return statements.
Document goto usage with comments.
Alternatives:
Methods to encapsulate control flow.
Boolean flags for conditional exits.
5. Practical Mini-Programs
Let’s apply these concepts in three practical mini-programs: a calculator, an even/odd checker, and a number guessing game.
Mini-Program 1: Calculator
A console app for basic arithmetic operations.
using System;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("\nSimple Calculator");
Console.WriteLine("1. Add");
Console.WriteLine("2. Subtract");
Console.WriteLine("3. Exit");
Console.Write("Choose an option: ");
string choice = Console.ReadLine();
if (choice == "3") break;
Console.Write("Enter first number: ");
if (!double.TryParse(Console.ReadLine(), out double num1))
{
Console.WriteLine("Invalid number!");
continue;
}
Console.Write("Enter second number: ");
if (!double.TryParse(Console.ReadLine(), out double num2))
{
Console.WriteLine("Invalid number!");
continue;
}
switch (choice)
{
case "1":
Console.WriteLine($"Result: {num1 + num2}");
break;
case "2":
Console.WriteLine($"Result: {num1 - num2}");
break;
default:
Console.WriteLine("Invalid option!");
break;
}
}
}
}
}
Features: Uses while, switch, break, continue, and arithmetic operators.
Real-World Use: Point-of-sale systems or financial tools.
Mini-Program 2: Even/Odd Checker
Checks if a number is even or odd.
using System;
namespace EvenOddChecker
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
if (!int.TryParse(Console.ReadLine(), out int number))
{
Console.WriteLine("Invalid input!");
return;
}
if (number % 2 == 0)
Console.WriteLine($"{number} is even.");
else
Console.WriteLine($"{number} is odd.");
}
}
}
Features: Uses if/else, modulus operator, and input validation.
Real-World Use: Validating data patterns (e.g., batch processing).
Mini-Program 3: Number Guessing Game
A game where the user guesses a random number.
using System;
namespace NumberGuessingGame
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int target = random.Next(1, 101); // Random number 1-100
int attempts = 0;
Console.WriteLine("Welcome to the Number Guessing Game!");
Console.WriteLine("Guess a number between 1 and 100.");
while (true)
{
Console.Write("Enter your guess: ");
if (!int.TryParse(Console.ReadLine(), out int guess) || guess < 1 || guess > 100)
{
Console.WriteLine("Invalid guess! Try again.");
continue;
}
attempts++;
if (guess == target)
{
Console.WriteLine($"Congratulations! You guessed it in {attempts} attempts!");
break;
}
else if (guess < target)
Console.WriteLine("Too low! Try again.");
else
Console.WriteLine("Too high! Try again.");
}
}
}
}
Features: Uses while, if/else, break, continue, relational/logical operators.
Real-World Use: Gamification in educational apps or user engagement tools.
Best Standards for Module 2
Operators: Use parentheses for clarity; validate inputs to avoid errors (e.g., division by zero).
If/Else: Keep conditions simple; use guard clauses to reduce nesting.
Switch: Prefer switch expressions (C# 8+) for concise code; include default cases.
Loops: Use foreach for collections, for for indexed iteration, while for condition-based loops.
Control Statements: Limit goto usage; prefer break/continue for loop control.
Mini-Programs: Validate all user inputs; provide clear feedback.
Conclusion
You’ve just mastered control flow and operators in C#! By learning arithmetic, relational, and logical operators, decision-making with if/else and switch, and iteration with loops, you’re now equipped to build dynamic, interactive programs. The calculator, even/odd checker, and number guessing game demonstrate how these concepts solve real-world problems.
0 comments:
Post a Comment