Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
74 changes: 74 additions & 0 deletions C# Language Features/Control Flow Statements/DoWhile/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
namespace DoWhileLoopExample;
class Program
{
/// <summary>
/// Main entry point of the application, demonstrating the use of a `do-while` loop.
/// The program repeatedly prompts the user to enter a positive number, validating input.
/// </summary>
static void Main(string[] args)
{
int number;

// do-while loop structure:
// The do-while loop executes a block of code once before checking the condition.
// After the first execution, it checks the condition to decide if the loop should continue.
//
// Syntax:
// do
// {
// // Code to execute at least once
// }
// while (condition);

// Begin do-while loop to ensure the code block runs at least once.
do
{
Console.Write("Please enter a positive number: ");

// Attempt to parse the input as an integer.
// If parsing fails, it will set number to -1 to ensure re-prompting in the loop.
bool isValidInput = int.TryParse(Console.ReadLine(), out number);

// Validation:
// - isValidInput checks if the input is a valid integer.
// - number > 0 ensures that the input is positive.
// If either condition fails, the loop will run again to re-prompt.
if (!isValidInput || number <= 0)
{
Console.WriteLine("Invalid input. Make sure to enter a positive number.\n");
}

} while (number <= 0); // Condition to keep looping if number is not positive.

// Once the user enters a valid positive number, the loop exits.
Console.WriteLine($"\nThank you! You've entered a positive number: {number}");

// Explanation of the do-while loop in this example:
// 1. The code inside the do block runs at least once, regardless of the condition.
// 2. After each execution, the while condition (number <= 0) is checked.
// 3. If the condition is true, the loop continues, re-prompting the user for input.
// 4. If the condition is false (i.e., a positive number is entered), the loop exits.

// Key Characteristics of a do-while loop:
// - Ensures that the code inside the loop runs at least once, even if the condition is initially false.
// - Typically used when we need one guaranteed execution (like prompting for user input).
// - The condition is evaluated only after the code block has executed.


// Best Practices for `do-while` Loops:

// 1. Use When at Least One Execution is Required:
// - `do-while` is best suited for scenarios where the loop body needs to run at least once, such as user input validation.

// 2. Avoid Using When Condition May Be Initially False:
// - Only use `do-while` when it's acceptable for the loop body to run even if the condition could initially be false.

// 3. Ensure Exit Condition is Reachable:
// - Make sure the loop body modifies a variable or state so that the `while` condition can eventually be false.
// - This helps avoid infinite loops and ensures the loop exits as expected.

// 4. Keep the Loop Body Short and Focused:
// - Since `do-while` loops can be harder to understand at a glance, aim to keep the body concise and clear.

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
77 changes: 77 additions & 0 deletions C# Language Features/Control Flow Statements/ForLoop/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
namespace ForLoopExample;
class Program
{
/// <summary>
/// Main entry point of the application, demonstrating the use of a `for` loop
/// by calculating the sum of numbers from 1 to a specified maximum.
/// </summary>
static void Main(string[] args)
{
// Define the maximum number for summation.
// This could come from user input or a data source in a real-world application.
int maxNumber = 10;
Console.WriteLine($"Calculating the sum of numbers from 1 to {maxNumber}...\n");

// for loop structure:
// The for loop is a control flow structure used to repeat a block of code a specific number of times.
// It consists of three main parts:
// 1. Initialization: Runs once before the loop starts. This sets up the loop variable (e.g., int i = 1).
// 2. Condition: Evaluated before each iteration. The loop continues as long as this condition is true (e.g., i <= maxNumber).
// 3. Iterator/Update: Runs after each loop iteration to update the loop variable (e.g., i++ to increment by 1).
//
// Syntax of a for loop:
// for (initialization; condition; update)
// {
// // Code to execute during each loop iteration
// }

// Variable to store the cumulative sum
int sum = 0;

// Begin for loop to calculate the sum from 1 to maxNumber.
for (int i = 1; i <= maxNumber; i++)
{
// Inside the loop:
// - i represents the current number being added to the sum.
// - The loop will run as long as i is less than or equal to maxNumber.

sum += i; // Add the current value of i to sum.

// Print each step to demonstrate the calculation in real-time.
Console.WriteLine($"Adding {i}, current sum: {sum}");
}

// Output the final sum after the loop completes.
Console.WriteLine($"\nThe total sum from 1 to {maxNumber} is: {sum}");

// Summary of the for loop in this example:
// 1. The loop starts with i = 1 (initialization).
// 2. It checks if i <= maxNumber before each loop (condition).
// 3. After each iteration, i is incremented by 1 (i++), progressing towards maxNumber.
// 4. The loop stops when i exceeds maxNumber, and the final sum is displayed.

// Advantages of using a for loop:
// - Provides a clear, concise syntax for repeating code with a known number of iterations.
// - Ideal for situations where you know the number of times the loop should run in advance.


// Best Practices for `for` Loops:

// 1. Choose the Right Loop Type:
// - Use a `for` loop when the number of iterations is known or can be calculated.
// - Avoid using `for` loops when a different structure (like `while`) would improve readability.

// 2. Avoid Modifying Loop Counter Inside the Loop Body:
// - Changing the loop variable (`i`) inside the loop body can lead to confusing and hard-to-debug code.
// - Instead, modify only within the loop’s initialization, condition, or increment sections.

// 3. Limit Scope of Loop Variables:
// - Use loop variables that are limited to the loop’s scope (e.g., `for (int i = 0; i < n; i++)`).
// - This helps prevent accidental misuse outside the loop.

// 4. Minimize Operations Inside the Loop Condition:
// - Avoid performing complex calculations in the loop condition as it will execute on every iteration.
// - Move constant expressions outside the loop for better performance.

}
}
10 changes: 10 additions & 0 deletions C# Language Features/Control Flow Statements/IfElse/IfElse.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
121 changes: 121 additions & 0 deletions C# Language Features/Control Flow Statements/IfElse/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
namespace IfElseExample;

class Program
{
/// <summary>
/// The main entry point of the application, which evaluates a student's score
/// and assigns a grade based on predefined criteria using if-else statements.
/// </summary>
static void Main(string[] args)
{
// Initialize a sample score for evaluation.
// In a real application, this score could be user input or retrieved from a database.
int score = 85;
Console.WriteLine("Student Score: " + score);

// if-else structure explanation:
// The if-else control structure allows us to execute code conditionally.
// Each 'if' checks a specific condition (a true/false statement).
// - If the condition evaluates to true, the associated block of code runs.
// - If false, it moves to the next 'else if' or 'else' block.
// This allows us to handle multiple scenarios in sequence, providing different outputs depending on the conditions.

// Basic syntax of if-else:
// if (condition)
// {
// // Code to run if condition is true
// }
// else if (anotherCondition)
// {
// // Code to run if previous condition is false, but this one is true
// }
// else
// {
// // Code to run if all previous conditions are false
// }

// Example of if-else in action:

if (score >= 90)
{
// This block executes if the score is 90 or above.
// 'if' keyword starts the condition, and the expression inside the parentheses (score >= 90)
// is the condition. Here, we're checking if 'score' is greater than or equal to 90.
// - If true: The statements inside this block run, assigning a grade of 'A'.
// - If false: It moves to the next 'else if' block.
Console.WriteLine("Grade: A");
Console.WriteLine("Remark: Excellent performance.");
}
else if (score >= 80)
{
// This block only runs if the previous 'if' condition is false (score < 90),
// and this condition (score >= 80) is true.
// 'else if' adds another condition to check after the initial 'if' fails.
// This block is only reached if the score is between 80 and 89.
Console.WriteLine("Grade: B");
Console.WriteLine("Remark: Good job! Keep pushing for an 'A'.");
}
else if (score >= 70)
{
// Additional 'else if' blocks can be added to handle more specific cases.
// This block only runs if both previous conditions (score >= 90 and score >= 80) are false,
// and if this condition (score >= 70) is true. In this case, it assigns a grade of 'C'.
Console.WriteLine("Grade: C");
Console.WriteLine("Remark: Fair effort, but there's room for improvement.");
}
else if (score >= 60)
{
// This block checks if all previous conditions are false and the score is between 60 and 69.
// The 'else if' is useful for checking a specific range and avoids redundant conditions.
Console.WriteLine("Grade: D");
Console.WriteLine("Remark: You passed, but aim for a higher score next time.");
}
else
{
// The 'else' statement catches any cases not covered by the previous conditions.
// - 'else' does not have a condition; it runs if none of the previous 'if' or 'else if' statements are true.
// This is a "catch-all" block for scores below 60, assigning a grade of 'F'.
Console.WriteLine("Grade: F");
Console.WriteLine("Remark: Unfortunately, this is a failing grade. Consider reviewing the material.");
}

// The if-else structure concludes here.
// Once a condition is met and its block runs, the entire structure is exited.
// For instance, if score is 85, only the 'else if (score >= 80)' block runs, and none of the others are checked.

// Final message for user interaction.
Console.WriteLine("\nGrade evaluation complete. Remember to keep improving and aim higher!");

// Summary of if-else control flow in this example:
// 1. The program checks each 'if' or 'else if' condition in order.
// 2. As soon as it finds a true condition, it executes that block and skips the rest.
// 3. If none of the conditions are true, it defaults to the 'else' block.
// This allows efficient branching where only one path is taken depending on the first true condition.


// Best Practices for `if-else` Statements:

// 1. Minimize Nested `if` Statements:
// - Deeply nested `if` statements can make code hard to read and maintain.
// - Use guard clauses to exit early, especially if certain conditions make further checks unnecessary.
// Example:
//if (!isValid) return; // Guard clause instead of additional nesting.

// 2. Use `else if` for Mutually Exclusive Conditions:
// - To avoid multiple `else` levels, use `else if` for conditions that are mutually exclusive.
// - This improves readability and avoids unnecessary condition checks.

// 3. Avoid Redundant Conditions:
// - If conditions overlap, ensure that only the necessary checks are used.
// - Redundant checks can lead to inefficient code and may cause logical errors.

// 4. Be Cautious with Floating Point Comparisons:
// - When comparing floating-point numbers, avoid direct equality checks due to precision issues.
// - Instead, check if the difference is within a small tolerance, e.g., `Math.Abs(a - b) < tolerance`.

// 5. Use Ternary Operators for Simple Assignments:
// - For simple conditional assignments, consider using the ternary operator to keep the code concise.
// Example:
//int ageCategory = age > 18 ? "Adult" : "Minor";
}
}
Loading
Loading